diff --git a/AGENTS.md b/AGENTS.md index bc45186..2cd5575 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,8 +15,9 @@ This branch (`v3`) rebuilds Sausage. The plan and its decisions (D1, D2, …) ar (spawn, wait, kill). Do not add another one. Everything else uses standard WASI 0.2 interfaces: files through the VFS, `wasi:http` (the host API on its reserved host name, credential injection, signing), and `wasi:sockets`. -- **The credentials manager in the host is the one real security boundary.** Secrets never enter the - world. Approvals need a passkey. +- **The credentials manager in the host is the one real security boundary.** Its managed secrets never enter + the world. Approvals need a passkey. The one exception is the LLM proxy key in `/etc/sausage/config.yaml`. + The user keeps that key inside the world so agents can change their own setup. - **Native code is the exception.** The only native work for the world is the Rust builder, and it runs in user, mount and network namespaces. diff --git a/README.md b/README.md index e9f809c..28c289a 100644 --- a/README.md +++ b/README.md @@ -8,18 +8,24 @@ Read [Run Sausage v3 on Citadel](docs/RUNNING.md) for the console, approvals, mo ```sh nix build +result/bin/sausage init /path/to/world result/bin/sausage run /path/to/world result/bin/sausage sh /path/to/world -c 'echo hi | tr a-z A-Z; git --version' ``` The package includes the userland bundle. At world creation, the host copies its tools into `/bin` as `.wasm` files. -It also copies a committed source snapshot into `/src/sausage`. -The console uses `PI_PROXY_BASE_URL` and `PI_PROXY_API_KEY` from the host environment. -Secrets do not enter the world. +The bundle ships plain source files. `sausage init` creates their repository in `/src/sausage` with one commit on `main`. +The world config lives at `/etc/sausage/config.yaml`. +It defines the proxy, listener, standing agent, roster, and shared system prompt. +`init` fills proxy settings from `PI_PROXY_BASE_URL` and `PI_PROXY_API_KEY` when present. It asks nothing. +The host and chat can start with an empty proxy key. Model requests then name the config file in their error. +The proxy key in that file is intentionally visible to agents. Other managed secrets stay outside the world. +The chat and console use the configured standing conversation. A rename keeps that conversation. +Model, prompt, and proxy edits apply without a host restart. Listener edits require a restart. The host creates `world/` for the shared filesystem and `host/` for private runtime state under the supplied directory. -Services come from `/config/services.yaml` in the world. +Services come from `/etc/systemd/system` in the world. ## Repository diff --git a/agents/coordinator.md b/agents/coordinator.md deleted file mode 100644 index 7838c59..0000000 --- a/agents/coordinator.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -name: coordinator -description: Owns one feature, its assessment, decisions, verification, and submission. -family: default - ---- - -# Feature coordinator - -Own the problem and final verdict. Delegate execution, not judgment. Read relevant memory and repository instructions first. -For a small clear change, implement it yourself and run the required checks. -For a feature or exploration, assess first and change nothing until authorization arrives. -An assessment states complexity, approximate code delta, reuse, recommendation, a simpler alternative, risks, and numbered decisions. -Send it to @ultimate first. Ask the user after @ultimate recommends options, unless @ultimate supplies an authorized decision. - -## Execution - -After approval, use plan with binary acceptance criteria. Delegate independent reconnaissance to scout and bounded implementation to worker or designer. -A writing child gets a worktree. Each brief names the source repo, owned files, forbidden areas, known evidence, checks, and required report. -Never assign overlapping edits concurrently. Do not delegate requirements or the final verdict. -Inspect each child’s diff and actual check output. A claim or idle child is not evidence. -Land accepted workers into your checkout. Run the required checks on the combined result. -Give reviewer an immutable full-SHA base..head range, repo path, criteria, and validation evidence. Verify concrete findings yourself. -Children never push. Never commit, reset, or land in the user’s checkout to test a result. -Before workspace submit, report the outcome, exact checks, risks, and divergence from the task. -Every repository-specific branch or workspace operation must name the explicit source repo path. -If visual approval is required, ask the user for approval of the actual rendered result before submission. -P3 has no browser capture tools. Request images through the coordinator or user, and name any visual checks you cannot verify. - -## Progress - -While children run, state which replies you await. Never declare completion before their reports arrive. -End a turn only when a child, queued submission, or requested reply will wake you, or when you report a blocker. -A failed submission requires a fix at its cause. Never skip a check or extend its deadline to hide a failure. - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/designer.md b/agents/designer.md deleted file mode 100644 index 6ae85b5..0000000 --- a/agents/designer.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -name: designer -description: Builds bounded product design for CLIs, servers, and interfaces. -family: design -isolate: worktree -denyTools: [] ---- - -# Product designer - -Solve the user’s stated problem within the assigned interface scope. Do not change backend contracts or dependencies without authorization. -Identify the user, their goal, the first thing they must notice, and the most important action. -Match existing patterns. Use hierarchy, spacing, readable text, and concrete action labels. -For CLIs, review help text, stdout, stderr, exit status, and long or empty output. -For web interfaces, cover empty, loading, error, long content, keyboard use, narrow widths, and applicable themes. -Keep existing behavior and required checks intact. Name departures from the brief instead of silently changing its scope. -Inspect rendered output before visual claims. P3 has no browser capture tools. Request screenshots from the coordinator or user. -If images are unavailable, report visual verification as unverified. Automated checks do not replace visual approval. -Do not delegate or push. Make one focused commit with --no-gpg-sign. -Report the outcome, design decisions, divergence, image paths, exact checks, and remaining risks. -End with Status: DONE | PARTIAL | BLOCKED and Commit: the full SHA or none. - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/docs/README.md b/agents/docs/README.md deleted file mode 100644 index 6689638..0000000 --- a/agents/docs/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# World agents and families - -The built-in agent files live in `/src/sausage/agents/` in the world. -`models.json` is the world family file. It contains a map from each family to `model` and `thinking`. -Model references use proxy provider names, not subscription providers. The host owns credentials and injects them outside the world. - -| Family | Model | Thinking | -| --- | --- | --- | -| default, fast | openai/gpt-6.1-sol | medium | -| review | anthropic/claude-opus-5-5 | xhigh | -| research, design, lead | anthropic/claude-opus-5-5 | high | - -The default family selects its configured world model. It does not inherit a subscription model from the parent. -All independent reviewers use `review`. Architecture remains advisory. This choice follows D30 instead of Ultimate’s mixed-model defaults. -Scout uses `research`. Watcher uses `fast`. Worker and dream-pass retain `fast: true`. - -## File order and overlays - -The caller supplies fresh file contents and explicit paths on each discovery. The parser performs no I/O. -It reads sorted immediate `*.md` children of the built-in `agents/` directory, then `/.sausage/agents/`. -Later complete definitions replace earlier definitions by their frontmatter `name`, not their filename. -Invalid files produce errors and leave any earlier valid definition intact. -No user directory, trust layer, or additional extension roots participate. - -An overlay has `name` and `addTools`. Use `addTools: []` for settings only. An overlay cannot contain `tools`. -Its settings replace earlier settings. Its tools and denials accumulate without duplicates. -Its body appends under `## Project additions`. The original definition retains its path and source. -A family overlay without a model removes an earlier model pin. Unknown families fall back to `default`. -A model pin overrides its family. Explicit thinking overrides a model suffix and family thinking. -Without explicit thinking or a suffix, a model pin has no requested thinking level. -The caller supplies the configured model catalog. Unknown model pins produce discovery errors. - -`sausage-coordinator.md` ports Ultimate’s repo coordinator overlay. Its filename sorts after `coordinator.md`. -The eight base definitions plus three independent reviewers and this overlay total twelve files. -Do not rename the overlay before its base in lexical order. - -## Parser contract and tests - -`extensions/core/agents.ts` exports pure parse, discovery, overlay, family, and tool-selection functions. -It supports scalar fields and flow lists. It also supports block lists and folded descriptions from Ultimate’s parse tests. -It does not implement general YAML or a definition editor with serialization. -`toolsFor` filters supplied explicit or inherited tools without changes to the parent list. -The subagent extension still owns child-specific defaults and enforcement of the role instructions. -Tool lists and denials are workflow controls, not a new security boundary. - -Run the tiny runner from this repository root with Node 24 or newer: - -```sh -nix develop -c node extensions/core/agents.test.ts -``` - -The test runner uses Node filesystem and assertion APIs. The parser imports no Node APIs or packages. -Tests cover source parse errors, overlays, denials, model resolution, all twelve agent files, and all four skills. -These files define P3 behavior. They do not install the later runtime extensions or load the live world. diff --git a/agents/dream-pass.md b/agents/dream-pass.md deleted file mode 100644 index 08c20de..0000000 --- a/agents/dream-pass.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -name: dream-pass -description: Performs one read-only learning pass and proposes evidence-based changes. -family: fast -fast: true -tools: [read, bash, memory] ---- - -# Read-only dream pass - -Your brief names one pass: memory, failures, tools, corrections, codify, or project. -Use its handoff, supplied conversation evidence, memory, and explicit repository files. -Start from summaries. Inspect individual evidence only where a summary points to a concrete issue. -Do not edit, commit, change state, message anyone, or delegate. Use bash only for inspection. -P3 supplies no history-query tool. If the handoff lacks conversation evidence, name that limitation rather than invent a query. -Report the overall finding, then prioritized findings with conversation ids, commits, or path:line citations and observed counts. -Propose one change per slug with a title, size, risk, and evidence. -Memory changes use add, update, or delete operations with reasons, but you do not apply them. -Codify proposals name the memory they replace. Project proposals name the explicit repo and existing code they reuse. -Never propose a storage chapter switch. Name all checks you cannot perform. - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/models.json b/agents/models.json deleted file mode 100644 index 56eeba0..0000000 --- a/agents/models.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "default": { - "model": "openai/gpt-6.1-sol", - "thinking": "medium" - }, - "fast": { - "model": "openai/gpt-6.1-sol", - "thinking": "medium" - }, - "review": { - "model": "anthropic/claude-opus-5-5", - "thinking": "xhigh" - }, - "research": { - "model": "anthropic/claude-opus-5-5", - "thinking": "high" - }, - "design": { - "model": "anthropic/claude-opus-5-5", - "thinking": "high" - }, - "lead": { - "model": "anthropic/claude-opus-5-5", - "thinking": "high" - } -} diff --git a/agents/reviewer-architecture.md b/agents/reviewer-architecture.md deleted file mode 100644 index adb9e50..0000000 --- a/agents/reviewer-architecture.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -name: reviewer-architecture -description: Advisory review against the Sausage world and durable extension architecture. -family: review -tools: [read, bash] ---- - -Independently inspect the explicit repo and immutable full-SHA base..head range with git log and git diff. -Never substitute a range. If it is missing or ambiguous, stop and report blocked verification. -Do not read other reviewers’ reports. Report only concrete issues introduced by this range. -Stay read-only. Do not edit, commit, push, change task status, run scripts, launch children, or delegate. -The lead starts reviewers in parallel and merges their findings. The coordinator owns the final verdict. - -Ask whether the range uses Sausage architecture instead of a parallel mechanism. -Read AGENTS.md and relevant extension contracts before judgment. -Check standard WASI files, HTTP, and sockets. The process interface is the only extra host import. -Host code accesses the world through the VFS. Native work belongs only to the isolated Rust builder. -Agents write CLIs and servers. Repos use explicit paths. Durable tasks and events should reuse existing extension contracts. -Name the existing piece and simpler alternative with path:line evidence. Leave correctness to its reviewer. -This review is advisory. Always report APPROVED, even when verification is blocked, and clearly state that limitation. -Architecture findings are P3 and never block. - -P0 means breakage, data loss, or exposed secrets. P1 means likely functional failure. -P2 blocks only when acceptance criteria require it. P3 means nonblocking polish. -Start with APPROVED or NEEDS CHANGES. The advisory architecture reviewer always uses APPROVED. -Report Reviewed range, Findings, Verification, and Residual risks. -Each finding states priority, title, path:line, impact, evidence, and a suggested fix. -NEEDS CHANGES means blocking findings or blocked verification. Never imply checks you did not run. - - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/reviewer-correctness.md b/agents/reviewer-correctness.md deleted file mode 100644 index c3483ed..0000000 --- a/agents/reviewer-correctness.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -name: reviewer-correctness -description: Correctness, credential safety, durability, and regression review. -family: review -tools: [read, bash] ---- - -Independently inspect the explicit repo and immutable full-SHA base..head range with git log and git diff. -Never substitute a range. If it is missing or ambiguous, stop and report blocked verification. -Do not read other reviewers’ reports. Report only concrete issues introduced by this range. -Stay read-only. Do not edit, commit, push, change task status, run scripts, launch children, or delegate. -The lead starts reviewers in parallel and merges their findings. The coordinator owns the final verdict. - -Check functional behavior, VFS mistakes, credential injection, 403 approvals, durable replay, duplicate effects, and caller regressions. -Do not invent per-agent security walls. The host credential manager is the security boundary. -For changed APIs, tools, documents, or events, inspect test doubles and fixtures for stale contracts. - -P0 means breakage, data loss, or exposed secrets. P1 means likely functional failure. -P2 blocks only when acceptance criteria require it. P3 means nonblocking polish. -Start with APPROVED or NEEDS CHANGES. The advisory architecture reviewer always uses APPROVED. -Report Reviewed range, Findings, Verification, and Residual risks. -Each finding states priority, title, path:line, impact, evidence, and a suggested fix. -NEEDS CHANGES means blocking findings or blocked verification. Never imply checks you did not run. - - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/reviewer-simplicity.md b/agents/reviewer-simplicity.md deleted file mode 100644 index 34cbd7c..0000000 --- a/agents/reviewer-simplicity.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -name: reviewer-simplicity -description: Independent simplicity and test-quality review. -family: review -tools: [read, bash] ---- - -Independently inspect the explicit repo and immutable full-SHA base..head range with git log and git diff. -Never substitute a range. If it is missing or ambiguous, stop and report blocked verification. -Do not read other reviewers’ reports. Report only concrete issues introduced by this range. -Stay read-only. Do not edit, commit, push, change task status, run scripts, launch children, or delegate. -The lead starts reviewers in parallel and merges their findings. The coordinator owns the final verdict. - -Check that the range uses the least code that satisfies the criteria. -Flag dead code, needless abstractions, duplicated logic, speculative fallbacks, jargon, and tests that merely restate implementation. -Every behavior needs a test. Prefer fast core tests and actual regressions over unrealistic load or timing tests. - -P0 means breakage, data loss, or exposed secrets. P1 means likely functional failure. -P2 blocks only when acceptance criteria require it. P3 means nonblocking polish. -Start with APPROVED or NEEDS CHANGES. The advisory architecture reviewer always uses APPROVED. -Report Reviewed range, Findings, Verification, and Residual risks. -Each finding states priority, title, path:line, impact, evidence, and a suggested fix. -NEEDS CHANGES means blocking findings or blocked verification. Never imply checks you did not run. - - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/reviewer.md b/agents/reviewer.md deleted file mode 100644 index a7d6005..0000000 --- a/agents/reviewer.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -name: reviewer -description: Read-only review lead for an immutable commit range. -family: review -tools: [read, bash, subagent] ---- - -# Review lead - -Review the coordinator’s explicit repo, immutable full-SHA base..head range, and acceptance criteria. -A missing or ambiguous range blocks verification. Never substitute another range. -If reviewer-* definitions exist, start every one with the same brief. Do not share reports among reviewers. -Wait for complete answers. A failed or idle child without an answer counts as missing. -Merge findings without additions or omissions. Name every reviewer who raised each issue. Show disagreements explicitly. -APPROVED requires approval from every reviewer. Otherwise report NEEDS CHANGES. -Without a team, inspect git log, git diff, and relevant unchanged logic yourself. -Remain read-only. Do not edit, commit, push, run project scripts, or execute mutation-capable checks. -Read supplied validation output instead of rerunning suites. Report only issues the range introduces. -P0 means breakage, data loss, or exposed secrets. P1 means likely functional failure. -P2 blocks only if acceptance criteria require it. P3 means nonblocking polish. -Report the reviewed range, reviewer verdicts, blocking and nonblocking findings, disagreements, observed verification, and residual risks. -Each finding needs priority, path:line, impact, evidence, and a suggested fix. Never imply checks you did not run. - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/sausage-coordinator.md b/agents/sausage-coordinator.md deleted file mode 100644 index 1b57a48..0000000 --- a/agents/sausage-coordinator.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -name: coordinator -description: Coordinates one feature for @ultimate -family: lead -addTools: [] ---- diff --git a/agents/scout.md b/agents/scout.md deleted file mode 100644 index 37d0469..0000000 --- a/agents/scout.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -name: scout -description: Read-only reconnaissance of one code question with path:line evidence. -family: research -tools: [read, bash] ---- - -# Read-only reconnaissance - -Answer only the assigned question. Inspect the explicit repo with read and /bin programs through bash. -Use rg, ls, git log, git show, and git diff for inspection. Never change files or state. -Do not edit, commit, run project scripts, or delegate. -Return a short conclusion, then path:line evidence and brief quotations where needed. -Name everything you cannot find or verify. - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/ultimate.md b/agents/ultimate.md deleted file mode 100644 index 4d3a4f1..0000000 --- a/agents/ultimate.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -name: ultimate -description: 'The standing agent: starts branches, routes decisions, and maintains world memory.' -family: default -resident: true -tools: [read, bash, message, note, notify, automation, branch, compact, remember, memory, todo, goal, edit, write] ---- - -# Standing agent - -You are Ultimate, the user’s standing agent in Sausage. Keep this conversation for the user and branch reports. -Read /src/sausage/AGENTS.md, agent files, skills, and relevant extension documents before answers about the platform. -Read the how-sausage-works skill when the user asks for a walkthrough. - -## Branches and decisions - -Write configuration and memory yourself. Send product code to a coordinator through branch. -Every branch brief names its repo path, goal, scope, acceptance criteria, and relevant memory slugs. -A small clear change needs targeted checks. A feature needs an assessment before implementation unless the user explicitly waived it. -After authorization, the coordinator plans, implements, verifies, reviews, and submits. Never declare success from an idle branch. -Route decisions through message with numbered questions. Let coordinators ask their own decisions after you state your recommendation. -Ask the user unless their instructions, memory, or active goal already settle the decision. -During a hands-off goal, record each decision and its authority with goal. Credentials and approvals remain the user’s responsibility. -Report a completed submission with its commit, checks, and divergence. Never push without authorization. - -## Memory and open work - -Use memory to read facts and remember to apply add, update, and delete operations. -Record durable decisions, not state that the prompt already supplies. Never store secrets in memory. -Use todo for open work, not unanswered questions. Use message for branch replies and notify for requested updates. -On a failed run, inspect the supplied failure evidence before you resume the agent or request user action. -Use compact with a self-contained handoff when context grows large. -A dream is a read-only review of evidence and memory. Approved proposals become ordinary branches. Do not switch storage chapters. -Use automation for schedules, event conditions, or supervised scripts. Verify its state with automation list. -When the user requests specialization, read integrate-sausage and adopt-sausage-workflow before proposals. - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/watcher.md b/agents/watcher.md deleted file mode 100644 index 44129c7..0000000 --- a/agents/watcher.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -name: watcher -description: Writes and repairs one supervised automation script. -family: fast -tools: [read, write, edit, bash, automation] ---- - -# Automation script owner - -Own the executable run file and automation id supplied in the brief. Use a WASI program or a supported shell in /bin. -Prefer an existing blocking watch command over polling. Never poll faster than every 30 seconds. -Store seen ids and persistent state in the supplied AUTOMATION_STATE directory. -Print FIRE followed by the event description when the condition holds. Other stdout is progress. Never print credentials. -A one-shot script exits after FIRE. A recurring script must not repeat seen events. -If the recurring task explicitly permits completion, print DONE with a reason and exit zero when no work remains. -Use the explicit repo path and automation file path from the brief. Report edits that remain uncommitted. -Try the script briefly before automation resume with your id. -On failure, inspect the supplied log, fix the cause, and resume. If the task cannot work, escalate with evidence. -Every repair turn ends with automation resume or escalate. Keep reports short. - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/agents/worker.md b/agents/worker.md deleted file mode 100644 index 99d4c96..0000000 --- a/agents/worker.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -name: worker -description: Implements one bounded task and reports check evidence in a focused commit. -family: fast -fast: true -isolate: worktree -denyTools: [] ---- - -# Bounded implementer - -Implement exactly the assigned task in your worktree. Read the brief, repository instructions, and nearby code first. -Reuse existing helpers. Do not expand scope, redesign the plan, delegate, or push. Report missing context as BLOCKED. -Run the brief’s checks with /bin programs. Use targeted tests during iteration and required suites before the commit. -Every behavior needs a test. Retain tests for the core path and actual bugs. -Inspect the complete diff. Remove only your own temporary code. Stage only task files. -Create one focused commit with --no-gpg-sign. Never commit failed checks. - -## Report - -Status: DONE | PARTIAL | BLOCKED -Summary: the outcome or blocker. -Acceptance criteria: each criterion with observed command output or path:line evidence. -Validation: exact commands and results. Name all unverified checks. -Commit: the full SHA and subject, or none. -Divergence: differences from the brief, or None. -Risks: remaining risks, or none. -DONE requires evidence for every criterion. - -## World contract - -The world is one WASI sandbox. All agents see the same world. Use the programs in /bin through bash. -Use an explicit repo path for repository operations. Worktrees live at /worktrees/. -The host injects credentials. A 403 requests approval through the host. Never read, store, or print secrets. -Agents write CLIs and servers. Do not add host imports beyond the process interface. diff --git a/config/config.yaml b/config/config.yaml new file mode 100644 index 0000000..4af1a60 --- /dev/null +++ b/config/config.yaml @@ -0,0 +1,342 @@ +# Agents can edit this file. The proxy key is intentionally visible inside the world. +# Empty proxy settings allow the chat to start. Fill them before a model request. +proxy: + base_url: "" + api_key: "" +standing: sausage +# Listener changes require a host restart. +listener: + address: 127.0.0.1:8090 + origin: http://localhost:8090 +prompt: |- + ## Sausage and the world + + Sausage is a world of programs and durable agents. All agents see and change the same world. + Use the programs in /bin through bash. Use explicit repository paths. Worktrees live at /worktrees/. + The platform source lives in /src/sausage. Extensions reload after a commit to main. + /etc/sausage/config.yaml contains this shared prompt, the roster, the standing agent name, models, and proxy settings. + You can read and edit that file. Changes apply at the next run. Listener changes require a host restart. + The proxy key in that file is intentionally visible. Other secrets stay in the host credentials manager. + The host injects those credentials. A 403 requests approval. Never store secrets in memory or print them. + Agents write CLIs and servers. Do not add host imports beyond the process interface. + + ## Inspect the harness state + + Read the live harness state with curl http://host.sausage/harness/...: + - whoami: the conversation and program that calls the route. + - conversations: ids, titles, owners, models, thinking, tools, and running state. + - conversations/ID/entries?after=N: conversation entries after entry N. + - events?after=N: domain events after event N. + - models: available models. + - extensions: loaded extensions. + - credential-requests: pending credential requests. + Read /proc/processes for processes and /proc/extensions for extensions. + Example: curl -s http://host.sausage/harness/conversations | jaq '.conversations[] | {id, title, model: .agent.model}' +roster: +- name: coordinator + description: Coordinates one feature for the standing agent + model: anthropic/claude-opus-5-5 + thinking: high + prompt: |- + # Feature coordinator + + Own the problem and final verdict. Delegate execution, not judgment. Read relevant memory and repository instructions first. + For a small clear change, implement it yourself and run the required checks. + For a feature or exploration, assess first and change nothing until authorization arrives. + An assessment states complexity, approximate code delta, reuse, recommendation, a simpler alternative, risks, and numbered decisions. + Send it to the standing agent first. Ask the user after the standing agent recommends options, unless the standing agent supplies an authorized decision. + + ## Execution + + After approval, use plan with binary acceptance criteria. Delegate independent reconnaissance to scout and bounded implementation to worker or designer. + A writing child gets a worktree. Each brief names the source repo, owned files, forbidden areas, known evidence, checks, and required report. + Never assign overlapping edits concurrently. Do not delegate requirements or the final verdict. + Inspect each child’s diff and actual check output. A claim or idle child is not evidence. + Land accepted workers into your checkout. Run the required checks on the combined result. + Give reviewer an immutable full-SHA base..head range, repo path, criteria, and validation evidence. Verify concrete findings yourself. + Children never push. Never commit, reset, or land in the user’s checkout to test a result. + Before workspace submit, report the outcome, exact checks, risks, and divergence from the task. + Every repository-specific branch or workspace operation must name the explicit source repo path. + If visual approval is required, ask the user for approval of the actual rendered result before submission. + P3 has no browser capture tools. Request images through the coordinator or user, and name any visual checks you cannot verify. + + ## Progress + + While children run, state which replies you await. Never declare completion before their reports arrive. + End a turn only when a child, queued submission, or requested reply will wake you, or when you report a blocker. + A failed submission requires a fix at its cause. Never skip a check or extend its deadline to hide a failure. + + addTools: [] +- name: designer + description: Builds bounded product design for CLIs, servers, and interfaces. + isolate: worktree + denyTools: [] + model: anthropic/claude-opus-5-5 + thinking: high + prompt: |- + # Product designer + + Solve the user’s stated problem within the assigned interface scope. Do not change backend contracts or dependencies without authorization. + Identify the user, their goal, the first thing they must notice, and the most important action. + Match existing patterns. Use hierarchy, spacing, readable text, and concrete action labels. + For CLIs, review help text, stdout, stderr, exit status, and long or empty output. + For web interfaces, cover empty, loading, error, long content, keyboard use, narrow widths, and applicable themes. + Keep existing behavior and required checks intact. Name departures from the brief instead of silently changing its scope. + Inspect rendered output before visual claims. P3 has no browser capture tools. Request screenshots from the coordinator or user. + If images are unavailable, report visual verification as unverified. Automated checks do not replace visual approval. + Do not delegate or push. Make one focused commit with --no-gpg-sign. + Report the outcome, design decisions, divergence, image paths, exact checks, and remaining risks. + End with Status: DONE | PARTIAL | BLOCKED and Commit: the full SHA or none. + +- name: dream-pass + description: Performs one read-only learning pass and proposes evidence-based changes. + fast: true + tools: + - read + - bash + - memory + model: openai/gpt-6.1-sol + thinking: medium + prompt: |- + # Read-only dream pass + + Your brief names one pass: memory, failures, tools, corrections, codify, or project. + Use its handoff, supplied conversation evidence, memory, and explicit repository files. + Start from summaries. Inspect individual evidence only where a summary points to a concrete issue. + Do not edit, commit, change state, message anyone, or delegate. Use bash only for inspection. + P3 supplies no history-query tool. If the handoff lacks conversation evidence, name that limitation rather than invent a query. + Report the overall finding, then prioritized findings with conversation ids, commits, or path:line citations and observed counts. + Propose one change per slug with a title, size, risk, and evidence. + Memory changes use add, update, or delete operations with reasons, but you do not apply them. + Codify proposals name the memory they replace. Project proposals name the explicit repo and existing code they reuse. + Never propose a storage chapter switch. Name all checks you cannot perform. + +- name: reviewer-architecture + description: Advisory review against the Sausage world and durable extension architecture. + tools: + - read + - bash + model: anthropic/claude-opus-5-5 + thinking: xhigh + prompt: |- + Independently inspect the explicit repo and immutable full-SHA base..head range with git log and git diff. + Never substitute a range. If it is missing or ambiguous, stop and report blocked verification. + Do not read other reviewers’ reports. Report only concrete issues introduced by this range. + Stay read-only. Do not edit, commit, push, change task status, run scripts, launch children, or delegate. + The lead starts reviewers in parallel and merges their findings. The coordinator owns the final verdict. + + Ask whether the range uses Sausage architecture instead of a parallel mechanism. + Read AGENTS.md and relevant extension contracts before judgment. + Check standard WASI files, HTTP, and sockets. The process interface is the only extra host import. + Host code accesses the world through the VFS. Native work belongs only to the isolated Rust builder. + Agents write CLIs and servers. Repos use explicit paths. Durable tasks and events should reuse existing extension contracts. + Name the existing piece and simpler alternative with path:line evidence. Leave correctness to its reviewer. + This review is advisory. Always report APPROVED, even when verification is blocked, and clearly state that limitation. + Architecture findings are P3 and never block. + + P0 means breakage, data loss, or exposed secrets. P1 means likely functional failure. + P2 blocks only when acceptance criteria require it. P3 means nonblocking polish. + Start with APPROVED or NEEDS CHANGES. The advisory architecture reviewer always uses APPROVED. + Report Reviewed range, Findings, Verification, and Residual risks. + Each finding states priority, title, path:line, impact, evidence, and a suggested fix. + NEEDS CHANGES means blocking findings or blocked verification. Never imply checks you did not run. + + +- name: reviewer-correctness + description: Correctness, credential safety, durability, and regression review. + tools: + - read + - bash + model: anthropic/claude-opus-5-5 + thinking: xhigh + prompt: |- + Independently inspect the explicit repo and immutable full-SHA base..head range with git log and git diff. + Never substitute a range. If it is missing or ambiguous, stop and report blocked verification. + Do not read other reviewers’ reports. Report only concrete issues introduced by this range. + Stay read-only. Do not edit, commit, push, change task status, run scripts, launch children, or delegate. + The lead starts reviewers in parallel and merges their findings. The coordinator owns the final verdict. + + Check functional behavior, VFS mistakes, credential injection, 403 approvals, durable replay, duplicate effects, and caller regressions. + Do not invent per-agent security walls. The host credential manager is the security boundary. + For changed APIs, tools, documents, or events, inspect test doubles and fixtures for stale contracts. + + P0 means breakage, data loss, or exposed secrets. P1 means likely functional failure. + P2 blocks only when acceptance criteria require it. P3 means nonblocking polish. + Start with APPROVED or NEEDS CHANGES. The advisory architecture reviewer always uses APPROVED. + Report Reviewed range, Findings, Verification, and Residual risks. + Each finding states priority, title, path:line, impact, evidence, and a suggested fix. + NEEDS CHANGES means blocking findings or blocked verification. Never imply checks you did not run. + + +- name: reviewer-simplicity + description: Independent simplicity and test-quality review. + tools: + - read + - bash + model: anthropic/claude-opus-5-5 + thinking: xhigh + prompt: |- + Independently inspect the explicit repo and immutable full-SHA base..head range with git log and git diff. + Never substitute a range. If it is missing or ambiguous, stop and report blocked verification. + Do not read other reviewers’ reports. Report only concrete issues introduced by this range. + Stay read-only. Do not edit, commit, push, change task status, run scripts, launch children, or delegate. + The lead starts reviewers in parallel and merges their findings. The coordinator owns the final verdict. + + Check that the range uses the least code that satisfies the criteria. + Flag dead code, needless abstractions, duplicated logic, speculative fallbacks, jargon, and tests that merely restate implementation. + Every behavior needs a test. Prefer fast core tests and actual regressions over unrealistic load or timing tests. + + P0 means breakage, data loss, or exposed secrets. P1 means likely functional failure. + P2 blocks only when acceptance criteria require it. P3 means nonblocking polish. + Start with APPROVED or NEEDS CHANGES. The advisory architecture reviewer always uses APPROVED. + Report Reviewed range, Findings, Verification, and Residual risks. + Each finding states priority, title, path:line, impact, evidence, and a suggested fix. + NEEDS CHANGES means blocking findings or blocked verification. Never imply checks you did not run. + + +- name: reviewer + description: Read-only review lead for an immutable commit range. + tools: + - read + - bash + - subagent + model: anthropic/claude-opus-5-5 + thinking: xhigh + prompt: |- + # Review lead + + Review the coordinator’s explicit repo, immutable full-SHA base..head range, and acceptance criteria. + A missing or ambiguous range blocks verification. Never substitute another range. + If reviewer-* definitions exist, start every one with the same brief. Do not share reports among reviewers. + Wait for complete answers. A failed or idle child without an answer counts as missing. + Merge findings without additions or omissions. Name every reviewer who raised each issue. Show disagreements explicitly. + APPROVED requires approval from every reviewer. Otherwise report NEEDS CHANGES. + Without a team, inspect git log, git diff, and relevant unchanged logic yourself. + Remain read-only. Do not edit, commit, push, run project scripts, or execute mutation-capable checks. + Read supplied validation output instead of rerunning suites. Report only issues the range introduces. + P0 means breakage, data loss, or exposed secrets. P1 means likely functional failure. + P2 blocks only if acceptance criteria require it. P3 means nonblocking polish. + Report the reviewed range, reviewer verdicts, blocking and nonblocking findings, disagreements, observed verification, and residual risks. + Each finding needs priority, path:line, impact, evidence, and a suggested fix. Never imply checks you did not run. + +- name: scout + description: Read-only reconnaissance of one code question with path:line evidence. + tools: + - read + - bash + model: anthropic/claude-opus-5-5 + thinking: high + prompt: |- + # Read-only reconnaissance + + Answer only the assigned question. Inspect the explicit repo with read and /bin programs through bash. + Use rg, ls, git log, git show, and git diff for inspection. Never change files or state. + Do not edit, commit, run project scripts, or delegate. + Return a short conclusion, then path:line evidence and brief quotations where needed. + Name everything you cannot find or verify. + +- name: sausage + description: "The standing agent: starts branches, routes decisions, and maintains world memory." + resident: true + tools: + - read + - bash + - message + - note + - notify + - automation + - branch + - compact + - remember + - memory + - todo + - goal + - edit + - write + model: anthropic/claude-opus-5-5 + thinking: high + prompt: |- + # Standing agent + + You are the user’s standing agent in Sausage. Keep this conversation for the user and branch reports. + Use the harness routes to answer questions about yourself and the world instead of guessing. + Inspect your own model, the conversation tree, and what branches do through those routes. + Read /src/sausage/AGENTS.md, the roster, skills, and relevant extension documents before answers about the platform. + Read the how-sausage-works skill when the user asks for a walkthrough. + + ## Branches and decisions + + Write configuration and memory yourself. Send product code to a coordinator through branch. + Every branch brief names its repo path, goal, scope, acceptance criteria, and relevant memory slugs. + A small clear change needs targeted checks. A feature needs an assessment before implementation unless the user explicitly waived it. + After authorization, the coordinator plans, implements, verifies, reviews, and submits. Never declare success from an idle branch. + Route decisions through message with numbered questions. Let coordinators ask their own decisions after you state your recommendation. + Ask the user unless their instructions, memory, or active goal already settle the decision. + During a hands-off goal, record each decision and its authority with goal. Credentials and approvals remain the user’s responsibility. + Report a completed submission with its commit, checks, and divergence. Never push without authorization. + + ## Memory and open work + + Use memory to read facts and remember to apply add, update, and delete operations. + Record durable decisions, not state that the prompt already supplies. Never store secrets in memory. + Use todo for open work, not unanswered questions. Use message for branch replies and notify for requested updates. + On a failed run, inspect the supplied failure evidence before you resume the agent or request user action. + Use compact with a self-contained handoff when context grows large. + A dream is a read-only review of evidence and memory. Approved proposals become ordinary branches. Do not switch storage chapters. + Use automation for schedules, event conditions, or supervised scripts. Verify its state with automation list. + When the user requests specialization, read integrate-sausage and adopt-sausage-workflow before proposals. + + + Act directly when the user asks you to change your setup. Edit /etc/sausage/config.yaml to change your model, the roster, or the proxy. You can read and edit that file, including the proxy key. Edit extensions in /src/sausage and commit to main to reload them. Edit the chat UI in /src/sausage/userland/chat, rebuild it with cargo build, and restart it with systemctl restart chat. Do not only describe these changes. Make them when requested. +- name: watcher + description: Writes and repairs one supervised automation script. + tools: + - read + - write + - edit + - bash + - automation + model: openai/gpt-6.1-sol + thinking: medium + prompt: |- + # Automation script owner + + Own the executable run file and automation id supplied in the brief. Use a WASI program or a supported shell in /bin. + Prefer an existing blocking watch command over polling. Never poll faster than every 30 seconds. + Store seen ids and persistent state in the supplied AUTOMATION_STATE directory. + Print FIRE followed by the event description when the condition holds. Other stdout is progress. Never print credentials. + A one-shot script exits after FIRE. A recurring script must not repeat seen events. + If the recurring task explicitly permits completion, print DONE with a reason and exit zero when no work remains. + Use the explicit repo path and automation file path from the brief. Report edits that remain uncommitted. + Try the script briefly before automation resume with your id. + On failure, inspect the supplied log, fix the cause, and resume. If the task cannot work, escalate with evidence. + Every repair turn ends with automation resume or escalate. Keep reports short. + +- name: worker + description: Implements one bounded task and reports check evidence in a focused commit. + fast: true + isolate: worktree + denyTools: [] + model: openai/gpt-6.1-sol + thinking: medium + prompt: |- + # Bounded implementer + + Implement exactly the assigned task in your worktree. Read the brief, repository instructions, and nearby code first. + Reuse existing helpers. Do not expand scope, redesign the plan, delegate, or push. Report missing context as BLOCKED. + Run the brief’s checks with /bin programs. Use targeted tests during iteration and required suites before the commit. + Every behavior needs a test. Retain tests for the core path and actual bugs. + Inspect the complete diff. Remove only your own temporary code. Stage only task files. + Create one focused commit with --no-gpg-sign. Never commit failed checks. + + ## Report + + Status: DONE | PARTIAL | BLOCKED + Summary: the outcome or blocker. + Acceptance criteria: each criterion with observed command output or path:line evidence. + Validation: exact commands and results. Name all unverified checks. + Commit: the full SHA and subject, or none. + Divergence: differences from the brief, or None. + Risks: remaining risks, or none. + DONE requires evidence for every criterion. + diff --git a/docs/RUNNING.md b/docs/RUNNING.md index 9897dda..5280093 100644 --- a/docs/RUNNING.md +++ b/docs/RUNNING.md @@ -14,11 +14,13 @@ Use Nix with flakes. The package supplies the native Rust builder and its tools. The package entry point is: ```sh +nix run . -- init "$HOME/sausage-v3" nix run . -- run "$HOME/sausage-v3" /.sausage/agents/`. -The models extension reads these files at each run boundary. Edits affect the next run without a restart. -An explicit model override can take precedence over a family. -The initial console root has a host-defined model. Do not assume a family edit changes every existing conversation. +Edit `standing` to select a roster member. The same standing conversation adopts its name, model, and role prompt. +The default member is `sausage`, with `anthropic/claude-opus-5-5` and `high` thinking. +Model and prompt edits apply at the next run without a restart. +Proxy edits apply before the next model request. Listener edits require a host restart. All real model requests retain the host proxy transport. Sources: [`credentials.rs`](../host/src/harness/credentials.rs), [`main.ts`](../host/js/main.ts), @@ -233,7 +239,7 @@ Keep credential approval and secret entry on host pages. | Method and route | Result or request | | --- | --- | -| `GET /harness/conversations` | Conversation records, titles, ownership, ancestry, and state. | +| `GET /harness/conversations` | Conversation records and `standing: {name, conversationId}` for the default selection. | | `GET /harness/conversations/ID/entries?after=0` | `{entries:[...]}` in ascending order. | | `GET /harness/conversations/ID/stream?after=0` | NDJSON entries, replay first, then live commits. | | `POST /harness/conversations/ID/submit` | `{content:"text",requestId:"stable-id"}` returns 202 and a submission ID. Reuse the request ID for retries. | @@ -241,7 +247,6 @@ Keep credential approval and secret entry on host pages. | `GET /harness/events?after=0` | NDJSON events, replay first, then live commits. | | `POST /harness/extensions/NAME/actions/ACTION` | `{args:{...},conversationId?:number}` invokes an exported user action. | | `GET /harness/models` | Public model catalog without authentication data. | -| `GET /harness/families` | World model families. | | `GET /harness/extensions` | Loaded extension status. | | `GET /harness/credential-requests` | Pending conversation requests with host approval links. | @@ -257,7 +262,6 @@ Source: [`host API contract`](../host/src/api/README.md), - Laptop access, passkey ceremonies, secret entry, and browser approval remain **to check with Surma**. - Startup checks use fake proxy credentials. They do not verify a real model session or external credential injection. -- A usable `llm-proxy` credential is mandatory even before the first chat. - The bootstrap chat is deliberately plain. There is no item editor or credential dashboard. - The console has no shell commands, transcript navigation, or special quit command. - `sausage sh` requires `-c`. Its interactive shell is not implemented. diff --git a/extensions/automations/README.md b/extensions/automations/README.md index 1e9d989..ae8cde7 100644 --- a/extensions/automations/README.md +++ b/extensions/automations/README.md @@ -54,7 +54,7 @@ For `idleFor`, admitted conversation inputs reset the idle period. ## Scope The initial port supports create, list, events, run, pause, resume, subscribe, unsubscribe, runs, log, and delete. -It retains the schedule and prompt-run implementation from Ultimate. +It retains the schedule and prompt-run implementation from Standing agent. It replaces native process groups with host Exec. Project-manifest discovery and automatic script repair remain outside this initial port. Credentials use grants, not named secret files. diff --git a/extensions/automations/scheduler.ts b/extensions/automations/scheduler.ts index 2e8235a..d269f8e 100644 --- a/extensions/automations/scheduler.ts +++ b/extensions/automations/scheduler.ts @@ -220,7 +220,7 @@ export function scheduler( { phase: 'plan' } | { phase: 'sleep'; until: number } | { phase: 'fire'; until: number }, null >({ - name: 'ultimate.automation-scheduler', + name: 'standing.automation-scheduler', version: 1, initial: () => ({ phase: 'plan' }), phases: { diff --git a/extensions/automations/server.ts b/extensions/automations/server.ts index e29cf49..82309ac 100644 --- a/extensions/automations/server.ts +++ b/extensions/automations/server.ts @@ -10,8 +10,8 @@ import { fireText, doneText, trimLog } from './types.ts' import type { Args, Automation, Subscriber } from './types.ts' export type { Automation, Run } from './types.ts' export const AutomationsApi = {name:'automations'} -export const Automations = defineDoc<{next:number;automations:Record}>({kind:'ultimate.automations',version:1,scope:'session',checkpointWhen:()=>false,initial:()=>({next:1,automations:{}})}) -const Receipts = defineDoc>({kind:'ultimate.automation-receipts',version:1,scope:'task',checkpointWhen:()=>false,initial:()=>({})}) +export const Automations = defineDoc<{next:number;automations:Record}>({kind:'standing.automations',version:1,scope:'session',checkpointWhen:()=>false,initial:()=>({next:1,automations:{}})}) +const Receipts = defineDoc>({kind:'standing.automation-receipts',version:1,scope:'task',checkpointWhen:()=>false,initial:()=>({})}) const ScriptFires = defineDoc>({kind:'automations.script-fires',version:1,scope:'task',checkpointWhen:()=>false,initial:()=>({})}) const owner = {ownership:{kind:'conversation'},conversationId:ROOT,background:true} as const const terminal = {status:'terminal',outcome:{status:'completed',result:null}} as const diff --git a/extensions/automations/types.ts b/extensions/automations/types.ts index af2d6ac..975473c 100644 --- a/extensions/automations/types.ts +++ b/extensions/automations/types.ts @@ -100,7 +100,7 @@ export type CreateArgs = { subscribers?: Subscriber[] scope?: 'user' | 'project' slug?: string - /** A project script's standing agent to wake on every machine, `@name`; default `@ultimate`. */ + /** A project script's standing agent to wake on every machine, `@name`; default `the standing agent`. */ to?: string key?: string } @@ -113,7 +113,7 @@ export type Args = Partial & { reason?: string } export type Manifest = { name: string; ask: string; once: boolean; secrets?: string[]; to: string } -/** A standing agent's name as a subscriber or target: `@ultimate`. */ +/** A standing agent's name as a subscriber or target: `the standing agent`. */ export const STANDING = /^@[a-zA-Z0-9_-]+$/ /** How many unplanned script exits in a row escalate instead of waking the watcher again. */ export const FAILURE_LIMIT = 3 @@ -137,4 +137,4 @@ export function trimLog(text: string): string { } /** The task kind of an automation's prompt run, which owns the run's conversation. */ -export const RUN_TASK = 'ultimate.automation-run' +export const RUN_TASK = 'standing.automation-run' diff --git a/extensions/core/agents.test.ts b/extensions/core/agents.test.ts index 2c87f04..55b992e 100644 --- a/extensions/core/agents.test.ts +++ b/extensions/core/agents.test.ts @@ -1,148 +1,67 @@ -/** Node-only test runner. The implementation imports no Node APIs. Run from the repository root. */ +/** Pure YAML roster checks. Bundle with the host's yaml dependency and run from the repository root. */ import assert from 'node:assert/strict' -import { readFileSync, readdirSync } from 'node:fs' -import { parseDefinition, parseOverlay, parseFrontmatter, mergeOverlay, parseFamilies, discoverAgents, definitionRuns, toolsFor } from './agents.ts' +import { readFileSync, readdirSync, existsSync } from 'node:fs' +import { parseConfig, parseFrontmatter, definitionRuns, toolsFor } from './agents.ts' let count = 0 function test(name: string, run: () => void) { run(); console.log(`ok ${++count} - ${name}`) } -const definition = (fields = '', body = 'Original instructions') => `---\nname: scout\ndescription: Search\n${fields}\n---\n${body}\n` -const families = parseFamilies(readFileSync('agents/models.json', 'utf8')) -const models = [...new Set(Object.values(families).map(family => family.model))] -const discover = (files: { path: string; text: string }[]) => discoverAgents(files, '/src/sausage', '/repos/app', families, models) -const base = (fields = '') => ({ path: '/src/sausage/agents/scout.md', text: definition(fields) }) -const project = (text: string, filename = 'scout') => ({ path: `/repos/app/.sausage/agents/${filename}.md`, text }) +const text=readFileSync('config/config.yaml','utf8') +const config=parseConfig(text) +const fixture=()=>({standing:'worker',prompt:'Shared context',roster:[{name:'worker',description:'Worker',model:'faux/faux-1',thinking:'low',prompt:'Role context',tools:['read']}]}) -test('Pi parse case: folded description and block tool list', () => { - assert.deepEqual(parseDefinition('---\nname: scout\ndescription: >\n A read-only scout\n that searches.\nmodel: openai/gpt-6.1-sol\nthinking: max\ntools:\n - read\n - bash\n---\nSearch\n', 'scout.md'), { - name: 'scout', description: 'A read-only scout that searches.', path: 'scout.md', instructions: 'Search', model: models[0], thinking: 'max', tools: ['read', 'bash'], - }) +test('default config contains the full roster and the configured standing model',()=>{ + assert.deepEqual(config.definitions.map(d=>d.name),['coordinator','designer','dream-pass','reviewer-architecture','reviewer-correctness','reviewer-simplicity','reviewer','scout','sausage','watcher','worker']) + const standing=config.definitions.find(d=>d.name===config.standing)! + assert.deepEqual(definitionRuns(standing),{model:{provider:'anthropic',modelId:'claude-opus-5-5'},thinking:'high'}) + assert(standing.instructions.includes('systemctl restart chat')) + assert(standing.instructions.includes('instead of guessing')) }) -test('flow lists, quotes, booleans, and carriage returns', () => { - const parsed = parseDefinition(definition('tools: [read, "bash"]\nsummaries: false\nresident: true\nfast: false\nicon: NotebookPen\ntint: grey').replaceAll('\n', '\r\n'), 'test') - assert.deepEqual(parsed.tools, ['read', 'bash']); assert.equal(parsed.summaries, false) - assert.equal(parsed.resident, true); assert.equal(parsed.fast, false) - assert.equal(parseFrontmatter("---\nname: 'it''s'\n---\nBody").frontmatter.name, "it's") - const multiline = parseDefinition(definition('tools:\n [\n read,\n bash,\n ]\nfamily: research'), 'test') - assert.deepEqual(multiline.tools, ['read', 'bash']); assert.equal(multiline.family, 'research') - assert.deepEqual(parseDefinition(definition('tools: [read, "unknown,tool"]'), 'test').tools, ['read', 'unknown,tool']) +test('global prompt states each harness route, the proc files, and the config path',()=>{ + for(const value of ['http://host.sausage/harness/','whoami','conversations','conversations/ID/entries?after=N','events?after=N','models','extensions','credential-requests','/proc/processes','/proc/extensions','jaq','/etc/sausage/config.yaml']) assert(config.prompt.includes(value),value) }) -const errors: [string, string][] = [ - ['tools: [read, bash]\nthinking: nonsense', 'thinking must be one of'], - ['description: " "', 'description is required'], - ['name: a scout', 'name must be a nonempty identifier'], - ['tools: read', 'tools must be a list of tool names'], - ['tools: [read, 1]', 'tools must be a list of tool names'], - ['model: " "', 'model must be a nonempty string'], - ['tool: [read]', 'Unknown field: tool'], - ['isolate: remote', 'isolate must be none or worktree'], - ['summaries: never', 'summaries must be a boolean'], - ['resident: no', 'resident must be a boolean'], - ['fast: 1', 'fast must be a boolean'], - ['family: Bad', 'family must be a family name'], - ['icon: bad/icon', 'icon must be a lucide icon name'], - ['tint: brown', 'tint must be one of'], -] -for (const [field, error] of errors) test(`reject ${field}`, () => { - const text = field.startsWith('description:') ? definition().replace('description: Search', field) : field.startsWith('name:') ? definition().replace('name: scout', field) : definition(field) - assert.throws(() => parseDefinition(text, 'test'), { message: new RegExp(error) }) +test('YAML block scalars keep the shared and role prompts separate',()=>{ + assert(config.prompt.startsWith('## Sausage and the world')) + assert(config.prompt.includes('\n\n## Inspect the harness state')) + assert(!config.prompt.includes('# Standing agent')) + assert(config.definitions.every(d=>d.instructions.includes('\n'))) }) -test('reject absent fields, empty instructions, and malformed blocks', () => { - for (const text of ['Text', '---\n---\nBody', '---\n- name\n---\nBody', '---\nname: scout\n']) assert.throws(() => parseDefinition(text, 'test'), /Expected frontmatter/) - assert.throws(() => parseDefinition(definition().replace('description: Search\n', ''), 'test'), /description is required/) - assert.throws(() => parseDefinition(definition('', ''), 'test'), /Instructions are required/) +test('JSON is valid YAML and model references preserve slashes in the model id',()=>{ + const value=fixture();value.roster[0].model='faux/org/model' + assert.deepEqual(definitionRuns(parseConfig(JSON.stringify(value)).definitions[0]).model,{provider:'faux',modelId:'org/model'}) }) -test('denyTools accepts unknown names and rejects invalid values for definitions and overlays', () => { - assert.deepEqual(parseDefinition(definition('denyTools: [instance, unknown-tool]'), 'test').denyTools, ['instance', 'unknown-tool']) - assert.deepEqual(parseDefinition(definition('denyTools: []'), 'test').denyTools, []) - for (const value of ['instance', '[instance, 1]', 'null', '{instance: true}']) { - assert.throws(() => parseDefinition(definition(`denyTools: ${value}`), 'test'), /denyTools must be a list/) - assert.throws(() => parseOverlay(definition(`addTools: []\ndenyTools: ${value}`), 'test'), /denyTools must be a list/) +test('reject missing global prompt, unknown standing name, and duplicate roster names',()=>{ + const value=fixture() + assert.throws(()=>parseConfig(JSON.stringify({...value,prompt:null})),/prompt must be a string/) + assert.throws(()=>parseConfig(JSON.stringify({...value,standing:'missing'})),/standing must name a roster member/) + assert.throws(()=>parseConfig(JSON.stringify({...value,roster:[...value.roster,...value.roster]})),/duplicate agent/) +}) +test('reject malformed YAML and invalid roster fields',()=>{ + assert.throws(()=>parseConfig('roster: [\n')) + for(const patch of [{name:'with space'},{description:''},{prompt:''},{model:'missing-provider'},{thinking:'no'},{tools:'read'},{denyTools:[1]}]) { + const value=fixture();Object.assign(value.roster[0],patch) + assert.throws(()=>parseConfig(JSON.stringify(value)),/config.yaml/) } }) -test('ordered overlays add tools and append bodies without changing source', () => { - const found = discover([project('---\nname: scout\naddTools: [write, read]\n---\nFirst', '01'), base('tools: [read, bash]'), project('---\nname: scout\naddTools: [message]\n---\nSecond', '02')]) - assert.deepEqual(found.errors, []); assert.deepEqual(found.replaced, []) - const agent = found.definitions[0] - assert.equal(agent.source, 'builtin'); assert.equal(agent.path, base().path) - assert.deepEqual(agent.tools, ['read', 'bash', 'write', 'message']) - assert.equal(agent.instructions, 'Original instructions\n\n## Project additions\n\nFirst\n\n## Project additions\n\nSecond') - assert.deepEqual(agent.overlays, [project('', '01').path, project('', '02').path]) +test('tool denials also apply to inherited tools without changing the parent',()=>{ + const definition=parseConfig(JSON.stringify(fixture())).definitions[0] + const parent=['read','write'] + delete definition.tools;definition.addTools=['bash'];definition.denyTools=['write'] + assert.deepEqual(toolsFor(definition,parent),['read','bash']) + assert.deepEqual(parent,['read','write']) }) -test('overlay settings replace while denials accumulate through empty overlay', () => { - const found = discover([base('tools: [read]\ndenyTools: [unknown-tool]\nthinking: low'), project('---\nname: scout\naddTools: []\ndenyTools: [unknown-tool, bash]\nmodel: anthropic/claude-opus-5-5\nthinking: high\nfast: true\ndescription: Our scout\n---', '01'), project('---\nname: scout\naddTools: []\ndenyTools: []\n---', '02')]) - assert.deepEqual(found.errors, []) - assert.deepEqual(found.definitions[0].denyTools, ['unknown-tool', 'bash']) - assert.equal(found.definitions[0].thinking, 'high'); assert.equal(found.definitions[0].fast, true) - assert.equal(found.definitions[0].description, 'Our scout') - assert.deepEqual(found.definitions[0].tools, ['read']) +test('skill frontmatter uses the same YAML parser',()=>{ + const parsed=parseFrontmatter('---\r\nname: skill\r\ndescription: >\r\n First line\r\n second line\r\n---\r\nBody') + assert.equal(parsed.frontmatter.name,'skill') + assert.equal(parsed.frontmatter.description,'First line second line\n') + assert.equal(parsed.body,'Body') }) -test('inherited tools retain deferred additions and do not mutate parent', () => { - const parent = ['read', 'bash', 'write', 'subagent'] - const child = mergeOverlay(parseDefinition(definition('denyTools: [write, subagent]'), 'test'), parseOverlay('---\nname: scout\naddTools: [message]\n---', 'overlay')) - assert.equal(child.tools, undefined); assert.deepEqual(child.addTools, ['message']) - assert.deepEqual(toolsFor(child, parent), ['read', 'bash', 'message']) - assert.deepEqual(toolsFor(parseDefinition(definition('tools: [read, write]\ndenyTools: [write]'), 'test'), parent), ['read']) - assert.deepEqual(parent, ['read', 'bash', 'write', 'subagent']) -}) -test('overlay errors do not replace a valid base', () => { - const found = discover([base(), project('---\nname: scout\naddTools: [x]\ntools: [read]\n---', 'listed'), project('---\nname: scout\naddTools: []\ncolour: red\n---', 'unknown'), project('---\nname: nobody\naddTools: [x]\n---', 'orphan')]) - assert.deepEqual(Object.fromEntries(found.errors.map(error => [error.name, error.error])), { - listed: 'Error: An overlay adds tools with addTools, not tools', unknown: 'Error: Unknown field: colour', orphan: 'Error: addTools needs an earlier definition named nobody', - }) - assert.equal(found.definitions[0].instructions, 'Original instructions') - assert.throws(() => parseOverlay('---\nname: scout\naddTools: read\n---', 'test'), /addTools must be a list/) -}) -test('replacement uses name, not filename, and respects exact roots', () => { - const found = discover([base(), project(definition('family: research', 'Replacement'), 'different'), { path: '/repos/other/.sausage/agents/scout.md', text: definition() }, { path: '/src/sausage/agents/nested/no.md', text: definition() }]) - assert.deepEqual(found.errors, []); assert.equal(found.definitions.length, 1) - assert.equal(found.definitions[0].source, 'project'); assert.equal(found.definitions[0].instructions, 'Replacement') - assert.deepEqual(found.replaced, [{ name: 'scout', path: project('', 'different').path, source: 'project' }]) -}) -test('family fallback, thinking override, model suffix, and unknown models', () => { - const run = (fields: string) => definitionRuns(parseDefinition(definition(fields), 'test'), families, models) - assert.equal(run('family: missing').family, 'default') - assert.equal(run('family: constructor').family, 'default') - assert.equal(run('family: research').thinking, 'high') - assert.equal(run('family: research\nthinking: low').thinking, 'low') - assert.equal(run('model: openai/gpt-6.1-sol').thinking, undefined) - assert.equal(run('model: openai/gpt-6.1-sol:high').thinking, 'high') - assert.equal(run('model: openai/gpt-6.1-sol:high\nthinking: low').thinking, 'low') - for (const model of ['anthropic/unknown', 'unknown']) assert.match(discover([base(`model: ${model}`)]).errors[0].error, /model: Model .* not found/) - const found = discover([base('model: openai/gpt-6.1-sol'), project('---\nname: scout\nfamily: lead\naddTools: []\n---')]) - assert.equal(found.definitions[0].model, undefined); assert.equal(found.definitions[0].runs.family, 'lead') - const suffix = discover([base('thinking: low'), project('---\nname: scout\nmodel: openai/gpt-6.1-sol:high\naddTools: []\n---')]) - assert.equal(suffix.definitions[0].runs.thinking, 'high') -}) -test('family world file requires valid refs and default', () => { - for (const text of ['null', '[]', '{}', '{"default":{"model":"bad"}}', '{"Default":{"model":"openai/a"}}', '{"default":{"model":"openai/a","thinking":"bad"}}']) assert.throws(() => parseFamilies(text)) - assert.deepEqual(Object.keys(families), ['default', 'fast', 'review', 'research', 'design', 'lead']) - assert.equal(families.review.thinking, 'xhigh') - assert.equal(families.design.thinking, 'high') -}) -test('all shipped definitions and overlays parse and discover', () => { - const files = readdirSync('agents').filter(name => name.endsWith('.md')).map(name => ({ path: `/src/sausage/agents/${name}`, text: readFileSync(`agents/${name}`, 'utf8') })) - assert.equal(files.length, 12) - const available = ['read', 'bash', 'edit', 'write', 'message', 'note', 'notify', 'automation', 'branch', 'compact', 'remember', 'memory', 'todo', 'goal', 'subagent', 'plan', 'workspace'] - for (const file of files) { - const agent = 'addTools' in parseFrontmatter(file.text).frontmatter ? parseOverlay(file.text, file.path) : parseDefinition(file.text, file.path) - assert.ok(!/\b(pnpm|vitest|clone|instance|restart|web_search|mcp|setup|codemode|debug)\b|~\/\.ultimate/.test(agent.instructions), file.path) - const fields = 'settings' in agent ? agent.settings : agent - for (const tool of [...(fields.tools ?? []), ...(fields.denyTools ?? []), ...('addTools' in agent ? agent.addTools ?? [] : [])]) assert.ok(available.includes(tool), `${file.path}: ${tool}`) +test('every built-in skill has its matching name, description, and instructions',()=>{ + for (const folder of readdirSync('skills')) { + const path=`skills/${folder}/SKILL.md` + if (!existsSync(path)) continue + const {frontmatter,body}=parseFrontmatter(readFileSync(path,'utf8')) + assert.equal(frontmatter.name,folder,path) + assert.equal(typeof frontmatter.description,'string',path) + assert(body.trim(),path) } - const found = discover(files) - assert.deepEqual(found.errors, []); assert.equal(found.definitions.length, 11) - assert.equal(found.definitions.find(agent => agent.name === 'coordinator')!.runs.family, 'lead') - for (const agent of found.definitions.filter(agent => agent.name.startsWith('reviewer'))) assert.equal(agent.runs.thinking, 'xhigh') }) -test('all applicable skills parse and avoid unavailable tools', () => { - let skills = 0 - for (const name of readdirSync('skills')) { - if (name === 'README.md') continue - const parsed = parseFrontmatter(readFileSync(`skills/${name}/SKILL.md`, 'utf8')) - assert.equal(parsed.frontmatter.name, name) - assert.equal(typeof parsed.frontmatter.description, 'string'); assert.ok(parsed.body) - assert.ok(!/\b(pnpm|vitest|clone|instance|restart|web_search|mcp|setup|codemode|debug)\b|~\/\.ultimate/.test(parsed.body), name) - skills++ - } - assert.equal(skills, 4) -}) -console.log(`${count} checks passed`) +console.log(`${count} tests passed`) diff --git a/extensions/core/agents.ts b/extensions/core/agents.ts index 042ace7..01f26b1 100644 --- a/extensions/core/agents.ts +++ b/extensions/core/agents.ts @@ -1,16 +1,15 @@ -/** Pure parsing and ordered overlays for world agent files. The caller supplies all file contents and model configuration. */ +/** YAML roster entries, skill metadata, model references, and inherited tools. */ +import { parse } from 'yaml' +export const CONFIG = '/etc/sausage/config.yaml' export const thinkingLevels = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const export type Thinking = typeof thinkingLevels[number] -export type Family = { model: string; thinking?: Thinking } -export type Families = Record export interface Definition { name: string description: string path: string instructions: string - model?: string + model: string thinking?: Thinking - family?: string tools?: string[] addTools?: string[] denyTools?: string[] @@ -20,152 +19,41 @@ export interface Definition { summaries?: boolean icon?: string tint?: string - overlays?: string[] } -export type File = { path: string; text: string } -const fields = ['name', 'description', 'model', 'thinking', 'family', 'tools', 'denyTools', 'isolate', 'resident', 'fast', 'summaries', 'icon', 'tint'] -const familyName = (name: string) => /^[a-z][a-z0-9-]{0,23}$/.test(name) -const tools = (value: unknown): value is string[] => Array.isArray(value) && value.every(v => typeof v === 'string') - -/** Scalars and flow lists, plus the block lists and folded description used in Ultimate's parser tests. Not general YAML. */ -function scalar(input: string): unknown { - const text = input.trim() - if (text.startsWith('[')) { - if (!text.endsWith(']')) throw new Error('Unclosed flow list') - const items = text.slice(1, -1).match(/\s*(?:"(?:\\.|[^"\\])*"|'(?:''|[^'])*'|[^,]+)/g) ?? [] - return items.filter(item => item.trim()).map(item => scalar(item)) - } - if (text.startsWith('"')) return JSON.parse(text) - if (text.startsWith("'")) { - if (!text.endsWith("'")) throw new Error('Unclosed scalar') - return text.slice(1, -1).replaceAll("''", "'") - } - if (text === 'true') return true - if (text === 'false') return false - if (text === 'null' || text === '~' || text === '') return null - if (/^-?\d+(\.\d+)?$/.test(text)) return Number(text) - if (text.startsWith('{')) return {} // Mapping values cannot satisfy any supported field. - return text.replace(/\s+#.*$/, '') +export function parseFrontmatter(text: string) { + const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(text) + if (!match) throw new Error('Expected frontmatter fields between --- lines') + return {frontmatter:parse(match[1]) as Record, body:match[2].trim()} } -export function parseFrontmatter(text: string): { frontmatter: Record; body: string } { - const lines = text.replaceAll('\r\n', '\n').split('\n') - const end = lines.indexOf('---', 1) - if (lines[0] !== '---' || end < 0) throw new Error('Expected frontmatter fields between --- lines') - const frontmatter: Record = {} - for (let i = 1; i < end; i++) { - if (!lines[i].trim() || lines[i].trimStart().startsWith('#')) continue - const match = /^([A-Za-z][A-Za-z0-9]*):\s*(.*)$/.exec(lines[i]) - if (!match) throw new Error('Expected frontmatter fields between --- lines') - const [, key, raw] = match - let value = raw - if (value.trim().startsWith('[') && !value.trim().endsWith(']')) { - while (i + 1 < end && !value.trim().endsWith(']')) value += ' ' + lines[++i].trim() - } - if (raw === '>' || raw === '|' || raw === '') { - const block: string[] = [] - while (i + 1 < end && /^\s+\S/.test(lines[i + 1])) block.push(lines[++i].trim()) - if (raw === '>') frontmatter[key] = block.join(' ') - else if (raw === '|') frontmatter[key] = block.join('\n') - else frontmatter[key] = block[0]?.startsWith('[') ? scalar(block.join(' ')) : block.length ? block.map(line => scalar(line.replace(/^-\s+/, ''))) : null - } else frontmatter[key] = scalar(value) - } - if (!Object.keys(frontmatter).length) throw new Error('Expected frontmatter fields between --- lines') - return { frontmatter, body: lines.slice(end + 1).join('\n').trim() } +export function parseRoster(text: string, path: string) { + const value = parse(text) + if (!value || !Array.isArray(value.roster)) throw new Error(`${path}: roster must be a list`) + const names = new Set() + const definitions = value.roster.map((entry: any): Definition => { + if (!entry || typeof entry.name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(entry.name)) throw new Error(`${path}: invalid roster name`) + if (names.has(entry.name)) throw new Error(`${path}: duplicate agent ${entry.name}`) + names.add(entry.name) + for (const key of ['description', 'prompt', 'model']) if (typeof entry[key] !== 'string' || !entry[key].trim()) throw new Error(`${path}: ${entry.name}.${key} is required`) + if (entry.thinking !== undefined && !thinkingLevels.includes(entry.thinking)) throw new Error(`${path}: invalid thinking for ${entry.name}`) + for (const key of ['tools', 'addTools', 'denyTools']) if (entry[key] !== undefined && (!Array.isArray(entry[key]) || !entry[key].every((tool: any)=>typeof tool === 'string'))) throw new Error(`${path}: ${entry.name}.${key} must be a list of tool names`) + const {prompt, ...settings} = entry + const definition = {...settings, path, instructions:prompt} + definitionRuns(definition) + return definition + }) + return {...value, definitions} } -function settings(data: Record, overlay: boolean) { - const unknown = Object.keys(data).find(key => !fields.includes(key) && !(overlay && key === 'addTools')) - if (unknown) throw new Error(`Unknown field: ${unknown}`) - if (typeof data.name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(data.name)) throw new Error('name must be a nonempty identifier') - for (const key of ['description', 'model']) { - if (data[key] !== undefined && (typeof data[key] !== 'string' || !data[key].trim())) throw new Error(key === 'description' ? 'description is required' : 'model must be a nonempty string') - } - if (data.family !== undefined && (typeof data.family !== 'string' || !familyName(data.family))) throw new Error('family must be a family name: lowercase letters, digits and -') - if (data.thinking !== undefined && !thinkingLevels.includes(data.thinking as Thinking)) throw new Error(`thinking must be one of ${thinkingLevels.join(', ')}`) - for (const key of ['tools', 'denyTools', 'addTools']) { - if (data[key] !== undefined && !tools(data[key])) throw new Error(`${key} must be a list of tool names`) - } - if (data.isolate !== undefined && data.isolate !== 'none' && data.isolate !== 'worktree') throw new Error('isolate must be none or worktree') - for (const key of ['resident', 'fast', 'summaries']) { - if (data[key] !== undefined && typeof data[key] !== 'boolean') throw new Error(`${key} must be a boolean`) - } - if (data.icon !== undefined && (typeof data.icon !== 'string' || !/^[A-Za-z][A-Za-z0-9]*(-[a-z0-9]+)*$/.test(data.icon))) throw new Error('icon must be a lucide icon name, like Gem or notebook-pen') - if (data.tint !== undefined && !['violet', 'blue', 'green', 'amber', 'red', 'pink', 'teal', 'grey'].includes(data.tint as string)) throw new Error('tint must be one of violet, blue, green, amber, red, pink, teal, grey') - return { ...data, ...(typeof data.description === 'string' ? { description: data.description.trim() } : {}) } -} -export function parseDefinition(text: string, path: string): Definition { - const { frontmatter, body } = parseFrontmatter(text) - const parsed = settings(frontmatter, false) - if (!parsed.description) throw new Error('description is required') - if (!body) throw new Error('Instructions are required') - return { ...parsed, path, instructions: body } as unknown as Definition -} -export function parseOverlay(text: string, path: string) { - const { frontmatter, body } = parseFrontmatter(text) - if ('tools' in frontmatter) throw new Error('An overlay adds tools with addTools, not tools') - const parsed = settings(frontmatter, true) - if (!tools(parsed.addTools)) throw new Error('addTools must be a list of tool names') - const { name, addTools, ...rest } = parsed - return { name: name as string, addTools, settings: rest as Partial, path, instructions: body } -} -export function mergeOverlay(base: Definition, overlay: ReturnType): Definition { - const { model: _pin, ...unpinned } = base - const suffix = overlay.settings.model?.match(/:(off|minimal|low|medium|high|xhigh|max)$/) - const resolved = suffix ? { ...overlay.settings, model: overlay.settings.model!.slice(0, -suffix[0].length), thinking: overlay.settings.thinking ?? suffix[1] as Thinking } : overlay.settings - return { - ...(overlay.settings.family && !overlay.settings.model ? unpinned : base), - ...resolved, - ...(overlay.settings.denyTools ? { denyTools: [...new Set([...(base.denyTools ?? []), ...overlay.settings.denyTools])] } : {}), - ...(base.tools ? { tools: [...new Set([...base.tools, ...overlay.addTools])] } : overlay.addTools.length ? { addTools: [...new Set([...(base.addTools ?? []), ...overlay.addTools])] } : {}), - instructions: overlay.instructions ? `${base.instructions}\n\n## Project additions\n\n${overlay.instructions}` : base.instructions, - overlays: [...(base.overlays ?? []), overlay.path], - } -} -export function parseFamilies(text: string): Families { - const value = JSON.parse(text) - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('families must be an object') - for (const [name, spec] of Object.entries(value) as [string, Family][]) { - if (!familyName(name) || !spec || typeof spec !== 'object' || !modelRef(spec.model)) throw new Error(`Invalid family: ${name}`) - if (spec.thinking !== undefined && !thinkingLevels.includes(spec.thinking)) throw new Error(`Invalid thinking for family: ${name}`) - } - if (!value.default) throw new Error('default family is required') +export function parseConfig(text: string) { + const value = parseRoster(text, CONFIG) + if (typeof value.prompt !== 'string') throw new Error(`${CONFIG}: prompt must be a string`) + if (!value.definitions.some((entry: Definition)=>entry.name === value.standing)) throw new Error(`${CONFIG}: standing must name a roster member`) return value } -function modelRef(model: unknown): model is string { return typeof model === 'string' && /^[^/\s]+\/\S+$/.test(model) } -export function definitionRuns(definition: Definition, families: Families, models: readonly string[]) { - const family = Object.hasOwn(families, definition.family ?? 'default') ? definition.family ?? 'default' : 'default' - let model = definition.model ?? families[family].model - let thinking = definition.thinking ?? (definition.model ? undefined : families[family].thinking) - const suffix = /:(off|minimal|low|medium|high|xhigh|max)$/.exec(model) - if (suffix) { model = model.slice(0, -suffix[0].length); thinking = definition.thinking ?? suffix[1] as Thinking } - if (!modelRef(model) || !models.includes(model)) throw new Error(`model: Model "${model}" not found`) - const slash = model.indexOf('/') - return { model: { provider: model.slice(0, slash), modelId: model.slice(slash + 1) }, thinking, ...(definition.model ? { via: 'pin' as const } : { via: 'family' as const, family }) } +export function definitionRuns(definition: Definition) { + if (!/^[^/\s]+\/\S+$/.test(definition.model)) throw new Error(`${definition.path}: invalid model for ${definition.name}`) + const slash = definition.model.indexOf('/') + return {model:{provider:definition.model.slice(0,slash),modelId:definition.model.slice(slash+1)},thinking:definition.thinking} } -/** Sorted built-ins precede sorted project files. Invalid files produce errors without replacing an earlier definition. */ -export function discoverAgents(files: readonly File[], builtinRoot: string, repo: string, families: Families, models: readonly string[]) { - const definitions = new Map() - const errors: { name: string; path: string; source: string; error: string }[] = [] - const replaced: { name: string; path: string; source: string }[] = [] - for (const [source, root] of [['builtin', builtinRoot + '/agents/'], ['project', repo + '/.sausage/agents/']] as const) { - for (const file of files.filter(file => file.path.startsWith(root) && !file.path.slice(root.length).includes('/') && file.path.endsWith('.md')).toSorted((a, b) => a.path.localeCompare(b.path))) { - try { - let definition: Definition - if ('addTools' in parseFrontmatter(file.text).frontmatter) { - const overlay = parseOverlay(file.text, file.path) - const base = definitions.get(overlay.name) - if (!base) throw new Error(`addTools needs an earlier definition named ${overlay.name}`) - definition = mergeOverlay(base, overlay) - } else definition = parseDefinition(file.text, file.path) - definitionRuns(definition, families, models) - const previous = definitions.get(definition.name) - if (source === 'project' && previous?.source === 'builtin' && !definition.overlays) replaced.push({ name: definition.name, path: file.path, source }) - definitions.set(definition.name, { ...definition, source: definition.overlays ? previous!.source : source }) - } catch (error) { errors.push({ name: file.path.split('/').at(-1)!.slice(0, -3), path: file.path, source, error: String(error) }) } - } - } - return { definitions: [...definitions.values()].map(definition => ({ ...definition, runs: definitionRuns(definition, families, models) })), errors, replaced } -} -/** Tool denials also apply to inherited tools. Inputs stay unchanged. */ export function toolsFor(definition: Definition, parent: readonly string[]): string[] { return [...new Set([...(definition.tools ?? parent), ...(definition.addTools ?? [])])].filter(tool => !definition.denyTools?.includes(tool)) } diff --git a/extensions/dream/DREAM.md b/extensions/dream/DREAM.md index f872abb..2ae09f2 100644 --- a/extensions/dream/DREAM.md +++ b/extensions/dream/DREAM.md @@ -3,7 +3,7 @@ A dream is a read-only review in an ordinary branch. It does not change code, memory, settings, or storage automatically. The user decides which proposals to accept. Approved proposals become ordinary work. -## For @ultimate +## For the standing agent A user request or a built-in automation can request a dream. If a dream branch is active, report that fact. Do not start another branch. @@ -43,12 +43,12 @@ Do not edit files, apply proposals, or switch storage during a dream. ## Built-in automations -Dream creates two ordinary context automations after @ultimate exists: +Dream creates two ordinary context automations after the standing agent exists: - `Dream before compaction`: the context exceeds 70%. - `Dream after a pause`: the context exceeds 50% after eight hours without user input. -The automations wake @ultimate. Each fire also adds one passive `dream.requested` entry. +The automations wake the standing agent. Each fire also adds one passive `dream.requested` entry. The automation ID and fire number identify that entry across replay and reopen. Creation keys recover a lost receipt without a duplicate automation. A user can pause or delete an automation. Reopen preserves those choices. diff --git a/extensions/dream/built-ins.ts b/extensions/dream/built-ins.ts index 65950b1..d4f8bbb 100644 --- a/extensions/dream/built-ins.ts +++ b/extensions/dream/built-ins.ts @@ -9,13 +9,14 @@ export const PAUSE_NAME='Dream after a pause' export const BuiltInDoc=defineDoc<{id?:string;deleted?:true}>({kind:'dream.after-compaction',version:1,scope:'conversation',history:'latest',fork:'initial',checkpointWhen:()=>false,initial:()=>({})}) export const PauseDoc=defineDoc<{id?:string;deleted?:true}>({kind:'dream.after-pause',version:1,scope:'conversation',history:'latest',fork:'initial',checkpointWhen:()=>false,initial:()=>({})}) const builtIns=[ - {doc:BuiltInDoc,name:AUTOMATION_NAME,condition:{metric:'context',of:'@ultimate',above:70}}, - {doc:PauseDoc,name:PAUSE_NAME,condition:{metric:'context',of:'@ultimate',above:50,idleFor:8*3600_000}}, + {doc:BuiltInDoc,name:AUTOMATION_NAME,condition:{metric:'context',above:70}}, + {doc:PauseDoc,name:PAUSE_NAME,condition:{metric:'context',above:50,idleFor:8*3600_000}}, ] -export const DREAM_ASK='Dream now: follow "For @ultimate" in /src/sausage/extensions/dream/DREAM.md. Write your handoff into the dream branch prompt in this turn, while your context still holds everything. If a dream branch is already active, say so and do not start another.' +export const DREAM_ASK='Dream now: follow "For the standing agent" in /src/sausage/extensions/dream/DREAM.md. Write your handoff into the dream branch prompt in this turn, while your context still holds everything. If a dream branch is already active, say so and do not start another.' export async function ensureAutomation(host:any) { const service=host.want(AutomationsApi) - if(!service || (await host.harness().snapshot(Standing,ROOT,context))?.ultimate===undefined) return + const standing=(await host.harness().snapshot(Standing,ROOT,context))?.['$standing'] + if(!service || standing===undefined) return for(const {doc,name,condition} of builtIns) { const state=await host.harness().snapshot(doc,ROOT,context) if(state?.deleted) continue @@ -23,7 +24,7 @@ export async function ensureAutomation(host:any) { const list=await service.operate({action:'list'}) if(!list.some((a:any)=>a.id===state.id)) await host.harness().commit(async(tx:any)=>{(await tx.doc(doc,ROOT)).deleted=true},context) } else { - const made=await service.operate({action:'create',name,condition,subscribers:['@ultimate'],key:`dream:${doc.definition.kind}`}) + const made=await service.operate({action:'create',name,condition:{...condition,of:`#${standing}`},subscribers:[standing],key:`dream:${doc.definition.kind}`}) await host.harness().commit(async(tx:any)=>{(await tx.doc(doc,ROOT)).id=made.id},context) } } @@ -31,10 +32,10 @@ export async function ensureAutomation(host:any) { export async function fired(host:any,tx:any,id:string,fire:number) { const builtIn=await Promise.all(builtIns.map(async(item)=>({item,id:(await tx.doc(item.doc,ROOT)).id}))) const found=builtIn.find(item=>item.id===id)?.item - const ultimate=(await tx.doc(Standing,ROOT)).ultimate - if(!found || ultimate===undefined) return + const standing=(await tx.doc(Standing,ROOT))['$standing'] + if(!found || standing===undefined) return const automation=(await tx.doc(Automations)).automations[id] const pause=found.doc===PauseDoc && automation ? Date.now()-(automation.condition?.inputAt??automation.createdAt) : undefined const data={automation:{id,name:automation?.name??found.name,...(pause===undefined?{}:{pause})}} - await deliver(host,tx,ultimate,{type:'write',requestId:`dream.requested:${id}:${fire}`,kind:'dream.requested',data,content:`Automation ${id} "${data.automation.name}" fired${pause===undefined?'':` after ${Math.round(pause/3600_000)} h away`}. ${DREAM_ASK}`}) + await deliver(host,tx,standing,{type:'write',requestId:`dream.requested:${id}:${fire}`,kind:'dream.requested',data,content:`Automation ${id} "${data.automation.name}" fired${pause===undefined?'':` after ${Math.round(pause/3600_000)} h away`}. ${DREAM_ASK}`}) } diff --git a/extensions/dream/server.ts b/extensions/dream/server.ts index e5b3757..070b5d7 100644 --- a/extensions/dream/server.ts +++ b/extensions/dream/server.ts @@ -27,22 +27,22 @@ export default function dream(host:any) { return run.catch((error:any)=>host.notice(`Dream automations: ${String(error)}`)) } host.onOpen(ensure) - host.react('ultimate-started',[Started],(_tx:any,{data}:any)=>{ + host.react('standing-started',[Started],(_tx:any,{data}:any)=>{ // Creation commits run after this reactor transaction completes. - if(data.kind==='standing'&&data.agent==='ultimate') void ensure() + if(data.kind==='standing') void ensure() },{from:'now'}) host.react('requested',[Fired],(tx:any,{data}:any)=>fired(host,tx,data.id,data.fire),{from:'now'}) async function change(tx:any,args:any) { - const ultimate=(await tx.doc(Standing,ROOT)).ultimate - if(ultimate===undefined) throw new Error('@ultimate has no conversation yet') + const standing=(await tx.doc(Standing,ROOT))['$standing'] + if(standing===undefined) throw new Error('the standing agent has no conversation yet') if(args.action==='start') { - await deliver(host,tx,ultimate,{type:'input',requestId:`dream.requested:${crypto.randomUUID()}`,kind:'dream.requested',data:{},content:`The user requested a dream. ${DREAM_ASK}`}) + await deliver(host,tx,standing,{type:'input',requestId:`dream.requested:${crypto.randomUUID()}`,kind:'dream.requested',data:{},content:`The user requested a dream. ${DREAM_ASK}`}) return {requested:true} } if(args.action!=='prepare') throw new Error(`Unknown dream action ${args.action}`) const prepared=prepare(args,Date.now()) ;(await tx.doc(Next,ROOT)).prepared=prepared - await deliver(host,tx,ultimate,{type:'write',requestId:`dream.prepared:${crypto.randomUUID()}`,kind:'dream.prepared',data:prepared,content:`Prepared dream handoff:\n${prepared.learned.join('\n')}\n\n${prepared.handoff}\nContinue in this world. No chapter switch is available.`}) + await deliver(host,tx,standing,{type:'write',requestId:`dream.prepared:${crypto.randomUUID()}`,kind:'dream.prepared',data:prepared,content:`Prepared dream handoff:\n${prepared.learned.join('\n')}\n\n${prepared.handoff}\nContinue in this world. No chapter switch is available.`}) return prepared } host.implement(DreamApi,{operate:(args:any)=>host.harness().commit((tx:any)=>change(tx,args),context)}) diff --git a/extensions/goal/README.md b/extensions/goal/README.md index ed18f71..05f2ca5 100644 --- a/extensions/goal/README.md +++ b/extensions/goal/README.md @@ -1,15 +1,15 @@ # Hands-off goals The user starts or ends a goal through the exported server actions. -Only the standing `@ultimate` conversation uses the `goal` tool. +Only the standing `the standing agent` conversation uses the `goal` tool. The root document stores one open goal and its decisions. Three failed tries block a criterion. Rewording preserves unchanged criteria. Decisions can name screenshots from the caller's conversation. The `latest` reference never crosses an input boundary. -Each input to `@ultimate` receives the current open goal note. +Each input to `the standing agent` receives the current open goal note. A queued start card grants nothing after the user ends the goal. -The start wakes `@ultimate`. The report uses a passive write. +The start wakes `the standing agent`. The report uses a passive write. The optional automations service creates one keyed reminder every 30 minutes. A durable task synchronizes its state after each lifecycle change. diff --git a/extensions/goal/delivery.ts b/extensions/goal/delivery.ts index 36e6ae2..f6c72dd 100644 --- a/extensions/goal/delivery.ts +++ b/extensions/goal/delivery.ts @@ -3,7 +3,7 @@ import { defineTask } from '@earendil-works/pi-durable' import type { ConversationId, Tx } from '@earendil-works/pi-durable' import type { Host } from '../../host/js/extensions.ts' -/** A goal card for @ultimate: `goal.started` as an input that wakes it, `goal.report` as a write. */ +/** A goal card for the standing agent: `goal.started` as an input that wakes it, `goal.report` as a write. */ type Card = { to: number; goal: number; kind: 'goal.started' | 'goal.report'; content: string } /** Created in the commit that changes the goal, so a crash cannot lose the card; the request id makes retries harmless. */ diff --git a/extensions/goal/refs.ts b/extensions/goal/refs.ts index a17dde1..3bd58df 100644 --- a/extensions/goal/refs.ts +++ b/extensions/goal/refs.ts @@ -1,7 +1,7 @@ -/** Hands-off goals in the browser: the goal the user put @ultimate on, and every decision it took for them. Browser-safe. */ +/** Hands-off goals in the browser: the goal the user put the standing agent on, and every decision it took for them. Browser-safe. */ import { actionRef, docRef } from '../goal/compat.ts' -/** One decision @ultimate took instead of asking the user. */ +/** One decision the standing agent took instead of asking the user. */ export type Decision = { at: number /** What it would have asked the user. */ @@ -11,19 +11,19 @@ export type Decision = { reason: string /** The branch the decision was for. */ conversation?: number - /** The entry of @ultimate's conversation holding the screenshots it judged, such as a UI preview it approved. */ + /** The entry of the standing agent's conversation holding the screenshots it judged, such as a UI preview it approved. */ images?: number } /** How a goal ended: met, blocked (every remaining criterion stuck), or ended by the user. */ export type Ending = { at: number - by: 'user' | 'ultimate' + by: 'user' | 'standing' outcome: 'met' | 'blocked' | 'ended' summary?: string } -/** What "done" means, as @ultimate wrote it down: each criterion open, met, or blocked after repeated failed tries. */ +/** What "done" means, as the standing agent wrote it down: each criterion open, met, or blocked after repeated failed tries. */ export type Criterion = { text: string; status: 'open' | 'met' | 'blocked'; tries?: number } export type Goal = { @@ -33,9 +33,9 @@ export type Goal = { startedAt: number criteria: Criterion[] decisions: Decision[] - /** The "Goal reminder" automation that wakes @ultimate every 30 minutes while the goal is open. */ + /** The "Goal reminder" automation that wakes the standing agent every 30 minutes while the goal is open. */ reminder?: string - /** Set while @ultimate is blocked on the user: the reminder is paused until it resumes. */ + /** Set while the standing agent is blocked on the user: the reminder is paused until it resumes. */ waiting?: { reason: string; at: number } ended?: Ending } @@ -43,12 +43,12 @@ export type Goal = { /** `{ next, goals }` on conversation 1, oldest first; at most one goal is open (no `ended`). */ export const GoalDoc = docRef<{ next: number; goals: Goal[] }>('goal') -/** `goal.started` and `goal.report` entries in @ultimate's conversation name their goal. */ +/** `goal.started` and `goal.report` entries in the standing agent's conversation name their goal. */ export type GoalEntry = { goal: number } -/** `{ text }` → the new goal. User-only: puts @ultimate hands-off on it. */ +/** `{ text }` → the new goal. User-only: puts the standing agent hands-off on it. */ export const StartAction = actionRef<{ text: string }, Goal>('goal', 'start') -/** No arguments → the ended goal. User-only: ends the open goal; @ultimate asks again as usual. */ +/** No arguments → the ended goal. User-only: ends the open goal; the standing agent asks again as usual. */ export const EndAction = actionRef('goal', 'end') /** `{ goal, entry }` → the images of a decision's screenshot entry. */ export const ImagesAction = actionRef< diff --git a/extensions/goal/reminder.ts b/extensions/goal/reminder.ts index 0ecfc5c..9667f46 100644 --- a/extensions/goal/reminder.ts +++ b/extensions/goal/reminder.ts @@ -1,5 +1,5 @@ /** - * The goal reminder: an automation that wakes @ultimate every 30 minutes while a goal is open, so a stalled goal never + * The goal reminder: an automation that wakes the standing agent every 30 minutes while a goal is open, so a stalled goal never * waits silently. Every goal change (start, pause, resume, end) creates a sync task in its own commit; the task brings * the automation in line with the goal as it is when the task runs. A crash leaves at most a task to rerun, and a rerun * gets the automation an earlier try made back from its create key instead of making a second one. @@ -9,6 +9,7 @@ import type { ConversationDocToken, Tx } from '@earendil-works/pi-durable' import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context' import type { Host } from '../../host/js/extensions.ts' import { AutomationsApi } from '../automations/server.ts' +import { Standing } from '../subagents/api.ts' import type { Automation } from '../automations/types.ts' import type { Goal } from './refs.ts' @@ -54,11 +55,12 @@ export function reminderTask(host: Host, Goals: Goals) { if (!own) { // One the user deleted in the Automations panel stays deleted. if (goal.reminder) return false + const standing = await host.harness().commit(async tx => (await tx.doc(Standing, ROOT_CONVERSATION_ID))['$standing'], context) await automations.operate({ action: 'create', name: reminderName(id), schedule: SCHEDULE, - subscribers: ['@ultimate'], + subscribers: [standing], key: reminderKey(id), }) return true diff --git a/extensions/goal/server.ts b/extensions/goal/server.ts index 24c34e6..73ba9c9 100644 --- a/extensions/goal/server.ts +++ b/extensions/goal/server.ts @@ -1,7 +1,7 @@ /** - * Hands-off goals: the user puts @ultimate on a goal and goes away. While it is open, @ultimate decides what it would + * Hands-off goals: the user puts the standing agent on a goal and goes away. While it is open, the standing agent decides what it would * otherwise ask them, records each decision with its reason, and ends the goal with a report. Only the user starts or - * ends a goal early; @ultimate hears it on every run through a per-input note. + * ends a goal early; the standing agent hears it on every run through a per-input note. */ import { arr, int, lit, obj, oneOf, opt, str, union } from '@earendil-works/pi-schema' import { @@ -42,7 +42,7 @@ export const docs = [Goals] /** A plain copy: the document's overlay is a proxy that structuredClone refuses, and unusable after the commit. */ const copy = (goal: Goal) => JSON.parse(JSON.stringify(goal)) as Goal -const ultimateOf = async (tx: Tx) => (await tx.doc(Standing, ROOT_CONVERSATION_ID)).ultimate +const standingOf = async (tx: Tx) => (await tx.doc(Standing, ROOT_CONVERSATION_ID))['$standing'] /** The open goal, if any. */ export async function openGoal(tx: Tx) { @@ -87,7 +87,7 @@ const status = (criterion: Criterion) => : criterion.status /** - * @ultimate's per-run note while a goal is open: the goal, its criteria, and how it works; on a fire of its reminder, + * the standing agent's per-run note while a goal is open: the goal, its criteria, and how it works; on a fire of its reminder, * what to check. */ export function noteText(goal: Goal, reminded = false) { @@ -135,8 +135,8 @@ type ToolArgs = { summary?: string } -/** One `goal` tool call by @ultimate (`ultimate`) in `tx`; returns its answer, and the goal when it finished. */ -export async function act(tx: Tx, ultimate: ConversationId, args: ToolArgs, now: number) { +/** One `goal` tool call by the standing agent (`standing`) in `tx`; returns its answer, and the goal when it finished. */ +export async function act(tx: Tx, standing: ConversationId, args: ToolArgs, now: number) { const goal = await openGoal(tx) if (!goal) throw new Error('No hands-off goal is open; ask the user as usual.') const criterion = () => { @@ -163,7 +163,7 @@ export async function act(tx: Tx, ultimate: ConversationId, args: ToolArgs, now: ...(args.conversation === undefined ? {} : { conversation: args.conversation }), ...(args.images === undefined ? {} - : { images: await imagesEntry(tx, ultimate, args.images) }), + : { images: await imagesEntry(tx, standing, args.images) }), } goal.decisions.push(decision) return { answer: `Recorded decision ${goal.decisions.length}: ${decision.picked}` } @@ -203,7 +203,7 @@ export async function act(tx: Tx, ultimate: ConversationId, args: ToolArgs, now: throw new Error("finish needs outcome 'met' or 'blocked'") const ended = await end(tx, { at: now, - by: 'ultimate', + by: 'standing', outcome: args.outcome, summary: text(args.summary, 'summary'), }) @@ -213,20 +213,20 @@ export async function act(tx: Tx, ultimate: ConversationId, args: ToolArgs, now: } } -/** The report card's model text: what @ultimate (or the user, ending it) should take from it. */ +/** The report card's model text: what the standing agent (or the user, ending it) should take from it. */ const reportText = (goal: Goal) => goal.ended?.by === 'user' ? `The user ended hands-off goal ${goal.id}. From now on ask them as usual.` : `Hands-off goal ${goal.id} ended (${goal.ended?.outcome}); its report card is here for the user. From now on ask them as usual.` /** - * Goal `goal`'s card of `kind` for @ultimate, delivered by a task created in `tx`, the commit that changed the goal. - * The start card says only that the user started it: what @ultimate may do comes from the goal note, built from the + * Goal `goal`'s card of `kind` for the standing agent, delivered by a task created in `tx`, the commit that changed the goal. + * The start card says only that the user started it: what the standing agent may do comes from the goal note, built from the * goal as it is when the input runs, so a start still queued after the user ended the goal grants nothing. */ async function card(host: Host, tx: Tx, kind: 'goal.started' | 'goal.report', goal: Goal) { - const to = await ultimateOf(tx) - if (to === undefined) throw new Error('@ultimate has no conversation yet') + const to = await standingOf(tx) + if (to === undefined) throw new Error('the standing agent has no conversation yet') await deliver(host, tx, { to, goal: goal.id, @@ -252,7 +252,7 @@ const sync = (host: Host, tx: Tx, goal: number) => }, ) -/** Starting and ending a goal is the user's grant; @ultimate only finishes one through its tool. */ +/** Starting and ending a goal is the user's grant; the standing agent only finishes one through its tool. */ export const userActions = ['start', 'end'] export const actions = { start: implementAction(StartAction, (args, { host }) => @@ -299,7 +299,7 @@ export default function goalExtension(host: Host) { // Pi upstream: @earendil-works/pi-durable@1.5.0 — patched transactional beforeInput hook. // A per-run note while a goal is open, never a system-prompt section, keeps the prompt cached. beforeInput: async (input, { tx, conversationId }) => { - if ((await ultimateOf(tx)) !== conversationId) return undefined + if ((await standingOf(tx)) !== conversationId) return undefined const goal = await openGoal(tx) if (!goal) return undefined // World automations use a plain input with their fire prefix. @@ -351,8 +351,8 @@ export default function goalExtension(host: Host) { async execute(args, api, ctx) { const caller = api.conversationId const result = await api.commit(async (tx) => { - if ((await ultimateOf(tx)) !== caller) - throw new Error('Only @ultimate keeps the hands-off goal.') + if ((await standingOf(tx)) !== caller) + throw new Error('Only the standing agent keeps the hands-off goal.') const acted = await act(tx, caller, args, Date.now()) if (acted.ended) await card(host, tx, 'goal.report', acted.ended) const changed = acted.sync ?? acted.ended?.id diff --git a/extensions/lineage/server.ts b/extensions/lineage/server.ts index 4b3d494..477effb 100644 --- a/extensions/lineage/server.ts +++ b/extensions/lineage/server.ts @@ -772,7 +772,7 @@ async function refuseTally(tx: Tx, id: ConversationId) { if (!(await tx.doc(Roots, ROOT_CONVERSATION_ID)).roots.includes(id)) return const tally = await tx.doc(Tally, id) if (tally.since !== undefined) - throw new Error(`#${id} is a tally and runs no turns; ask @ultimate to start a branch`) + throw new Error(`#${id} is a tally and runs no turns; ask the standing agent to start a branch`) } @@ -964,9 +964,9 @@ export default function lineageExtension(host: any) { async execute({ root, ops }, api, ctx) { // Every conversation sees the tool, but only the primary agent can write memory. const standing = await host.harness().snapshot(Standing, ROOT_CONVERSATION_ID, ctx) - if (standing?.ultimate !== api.conversationId) + if (standing?.['$standing'] !== api.conversationId) throw new Error( - 'Only @ultimate writes project memory; tell @ultimate what to remember (message, reply: false).', + 'Only the standing agent writes project memory; tell the standing agent what to remember (message, reply: false).', ) const id = await memoryRoot(api.conversationId, root, ctx) const summary = await applyMemoryOps(host, id, ops, Date.now(), `tool:${api.taskId}:${api.callId}`) diff --git a/extensions/messages/README.md b/extensions/messages/README.md index 911f828..0d81736 100644 --- a/extensions/messages/README.md +++ b/extensions/messages/README.md @@ -1,6 +1,6 @@ # Messages and lineage -The extensions preserve the durable `board.*` and `lineage.*` identifiers from Ultimate. +The extensions preserve the durable `board.*` and `lineage.*` identifiers from Standing agent. They use world files and world git. They do not use native filesystem or process APIs. ## Branches and delivery @@ -27,7 +27,7 @@ The starter's final answer reaches the branch without a faulted routing task. A static test checks free runtime identifiers in every extension module, including function bodies. The grant chain contains fork ancestry before starter ancestry. -Each conversation occurs once. A root fork that @ultimate starts includes `[branch, root, ultimate]`. +Each conversation occurs once. A root fork that the standing agent starts includes `[branch, root, standing]`. ## Tally and catch-up @@ -54,7 +54,7 @@ A shared queue serializes writes across extension reloads. A tool or landing receipt commits in that same file. Thus, a restart after the rename does not apply the operations twice. -Only @ultimate can use the `remember` tool. +Only the standing agent can use the `remember` tool. Other extensions can use the lineage service. Branches from a root with memory start with its index and recent landings. diff --git a/extensions/messages/addresses.ts b/extensions/messages/addresses.ts index 7159c95..676f496 100644 --- a/extensions/messages/addresses.ts +++ b/extensions/messages/addresses.ts @@ -36,9 +36,9 @@ export async function parentOf(host: ExtensionHost, id: number, ctx: Context) { } export async function senderName(host: ExtensionHost, id: number | 'user', ctx: Context) { if (id === 'user') return 'user' - if (typeof id !== 'number') return 'another Ultimate' + if (typeof id !== 'number') return 'another Standing agent' const index = await host.harness().snapshot(Standing, ROOT_CONVERSATION_ID, ctx) - const name = Object.keys(index ?? {}).find((candidate) => index?.[candidate] === id) + const name = Object.keys(index ?? {}).find((candidate) => candidate !== '$standing' && index?.[candidate] === id) return `#${id}${name ? ` (@${name})` : ''}` } export async function resolve( diff --git a/extensions/messages/api.ts b/extensions/messages/api.ts index f5917c8..600bdc2 100644 --- a/extensions/messages/api.ts +++ b/extensions/messages/api.ts @@ -37,7 +37,7 @@ export type Message = { echo?: true /** The questions a reply-expected message to the user asks, answered on its card. */ questions?: Question[] - /** A user answer or dismissal that @ultimate settled for the user, not their own click. */ + /** A user answer or dismissal that the standing agent settled for the user, not their own click. */ via?: Via } /** Every message between conversations and the user, on the root conversation. */ diff --git a/extensions/messages/delivery.ts b/extensions/messages/delivery.ts index e91f8d1..ad0ca54 100644 --- a/extensions/messages/delivery.ts +++ b/extensions/messages/delivery.ts @@ -34,7 +34,7 @@ export function delivery(host: ExtensionHost) { note: boolean fromLabel: string toLabel: string - /** Another project's Ultimate answered `message`: deliver only this reply. */ + /** Another project's Standing agent answered `message`: deliver only this reply. */ reply?: { message: Message; failed: boolean; stopped?: boolean } }, | { phase: 'deliver' } diff --git a/extensions/messages/notice.ts b/extensions/messages/notice.ts index 5231b30..6e5f299 100644 --- a/extensions/messages/notice.ts +++ b/extensions/messages/notice.ts @@ -1,4 +1,4 @@ -/** Passive context for @ultimate about a branch's questions to the user. */ +/** Passive context for the standing agent about a branch's questions to the user. */ import { defineTask } from '@earendil-works/pi-durable' import type { ConversationId } from '@earendil-works/pi-durable' import type { Host as ExtensionHost } from '../../host/js/extensions.ts' @@ -14,7 +14,7 @@ export const notice = (host: Pick) => call?: string summary?: string dismissed?: boolean - /** @ultimate settled it for the user. */ + /** the standing agent settled it for the user. */ via?: { conversation: number; entry?: number } } content: string diff --git a/extensions/messages/questions.ts b/extensions/messages/questions.ts index a9fe0d9..d42f71d 100644 --- a/extensions/messages/questions.ts +++ b/extensions/messages/questions.ts @@ -129,8 +129,8 @@ export const gist = (message: Pick) => { * open, so the agent treats them as unanswered. A per-input entry, not a system-prompt section, keeps the prompt cached. */ export async function openQuestionsNote(tx: Tx, conversationId: ConversationId, now: number) { - // @ultimate sees every open question to the user, since it settles those the user decides in its chat. - const primary = (await tx.doc(Standing, ROOT_CONVERSATION_ID)).ultimate === conversationId + // the standing agent sees every open question to the user, since it settles those the user decides in its chat. + const primary = (await tx.doc(Standing, ROOT_CONVERSATION_ID))['$standing'] === conversationId const open = (await tx.doc(Messages, ROOT_CONVERSATION_ID)).messages.filter( (m) => openQuestion(m) && (primary || m.from === conversationId), ) @@ -143,7 +143,7 @@ export async function openQuestionsNote(tx: Tx, conversationId: ConversationId, ) .join( '\n', - )}${primary ? `\nWhen the user decides one in your chat, settle it with ultimate.action('messages', 'settle', { messageId, text }).` : ''}` + )}${primary ? `\nWhen the user decides one in your chat, settle it with standing.action('messages', 'settle', { messageId, text }).` : ''}` return { entries: [ { diff --git a/extensions/messages/route.ts b/extensions/messages/route.ts index ff52ebb..036993f 100644 --- a/extensions/messages/route.ts +++ b/extensions/messages/route.ts @@ -46,7 +46,7 @@ async function live(tx: Tx, kind: string, conversationId?: ConversationId) { */ async function busy(tx: Tx, id: ConversationId) { if ((await tx.doc(LiveDoc, id)).run || (await tx.doc(InboxDoc, id)).items.length) return true - if ((await live(tx, 'ultimate.subagent-reporter', id)).length) return true + if ((await live(tx, 'standing.subagent-reporter', id)).length) return true return (await live(tx, 'lineage.notify', id)).some( (task) => (task.input as { wake?: unknown }).wake !== false, ) diff --git a/extensions/messages/send.ts b/extensions/messages/send.ts index d685946..b4c9e73 100644 --- a/extensions/messages/send.ts +++ b/extensions/messages/send.ts @@ -71,7 +71,7 @@ export async function send( /** Place it as a note, which starts no run; by default one-way messages to the sender's starter are notes. */ note?: boolean device?: Device - /** The user's answer or dismissal settled by @ultimate on their behalf, from their input `via.entry`. */ + /** The user's answer or dismissal settled by the standing agent on their behalf, from their input `via.entry`. */ via?: Via /** A branch's final answer routed as its report: the branch shows as awaiting its starter. */ report?: boolean @@ -91,7 +91,7 @@ export async function send( if (callId !== undefined && sent?.ids[callId] !== undefined) return sent.ids[callId] } const standing = await host.harness().snapshot(Standing, ROOT_CONVERSATION_ID, ctx) - const primaryId = standing?.ultimate + const primaryId = standing?.['$standing'] // The primary agent's messages to a busy conversation almost always steer it: new scope, a decision, a stop. const steer = input.steer ?? (from !== 'user' && from === primaryId) // Checked before resolving, which may create a standing agent's conversation. @@ -100,7 +100,7 @@ export async function send( if (input.to === 'user') { if (from !== primaryId && !(parent === undefined && starter !== undefined)) throw new Error( - 'Only @ultimate and branches message the user; send this to the conversation that started you.', + 'Only the standing agent and branches message the user; send this to the conversation that started you.', ) } if (!input.text.trim()) throw new Error('Message text must not be empty') @@ -113,7 +113,7 @@ export async function send( ) const to = await resolve(host, input.to, from, ctx) const fromLabel = via - ? `user (settled for them by @ultimate, from what they said in its chat)` + ? `user (settled for them by the standing agent, from what they said in its chat)` : await senderName(host, from, ctx) const toLabel = await senderName(host, to, ctx) return host.harness().commit(async (tx) => { @@ -261,7 +261,7 @@ export async function send( ) } // The user's answer or dismissal is their input to the asker; the message's `entry` names it once delivered. One - // @ultimate settled for them is not: their chat input that it came from counted already. + // the standing agent settled for them is not: their chat input that it came from counted already. if (from === 'user' && answerId !== undefined && typeof to === 'number' && !via) await host.emit(tx, UserInputEvent, { conversation: to, diff --git a/extensions/messages/server.ts b/extensions/messages/server.ts index c9749d5..74e60a8 100644 --- a/extensions/messages/server.ts +++ b/extensions/messages/server.ts @@ -26,7 +26,7 @@ async function openMessage(host: ExtensionHost, messageId: number, ctx: Context) if (!message || !openQuestion(message)) throw new Error('These questions are no longer open') return message } -/** The user's answer `text` to open message `messageId`, or @ultimate's on their behalf (`via`). */ +/** The user's answer `text` to open message `messageId`, or the standing agent's on their behalf (`via`). */ async function answer( host: ExtensionHost, messageId: number, @@ -35,7 +35,7 @@ async function answer( options: { device?: Device; via?: { via: Via; primary: number } } = {}, ) { const message = await openMessage(host, messageId, ctx) - // @ultimate settling its own question has the answer already: a one-way note, not another turn. + // the standing agent settling its own question has the answer already: a one-way note, not another turn. const own = options.via !== undefined && message.from === options.via.primary return send( host, @@ -50,7 +50,7 @@ async function answer( }, ) } -/** Close open message `messageId` unanswered: the user's dismissal, or @ultimate's on their behalf with `reason`. */ +/** Close open message `messageId` unanswered: the user's dismissal, or the standing agent's on their behalf with `reason`. */ async function dismiss( host: ExtensionHost, messageId: number, @@ -106,7 +106,7 @@ export default function messages(host: ExtensionHost) { let by = (await api.snapshot(Started, api.conversationId, ctx))?.by const down = by === undefined && - (await api.snapshot(Standing, ROOT_CONVERSATION_ID, ctx))?.ultimate === + (await api.snapshot(Standing, ROOT_CONVERSATION_ID, ctx))?.['$standing'] === api.conversationId if (down) by = api.conversationId if (by === undefined) return undefined @@ -146,7 +146,7 @@ export default function messages(host: ExtensionHost) { starter === undefined ? '' : ` #${starter} started you: when you stop with nothing under way (no subagent, landing or reply pending), your final answer goes to it and wakes it; while work is under way it arrives as a note, and so do your one-way messages to it.` - return `Use message to contact #id or @name. @ultimate and branches may message user. Messages wake their recipient; its answer returns as a reply and wakes you. End your turn instead of waiting. A one-way message (reply: false) gets no answer; use reply: true when you need one. Inputs identify their sender; answer here and your answer is sent to the sender automatically; do not use message to reply. A message to an agent whose message you still owe an answer becomes that answer and ends your run; use it only to attach images.${upward}\n${agents.map((a) => `@${a.name} — ${a.description}`).join('\n')}` + return `Use message to contact #id or @name. the standing agent and branches may message user. Messages wake their recipient; its answer returns as a reply and wakes you. End your turn instead of waiting. A one-way message (reply: false) gets no answer; use reply: true when you need one. Inputs identify their sender; answer here and your answer is sent to the sender automatically; do not use message to reply. A message to an agent whose message you still owe an answer becomes that answer and ends your run; use it only to attach images.${upward}\n${agents.map((a) => `@${a.name} — ${a.description}`).join('\n')}` }), ], tools: [ @@ -154,7 +154,7 @@ export default function messages(host: ExtensionHost) { defineTool({ name: 'message', description: - 'Send a message to #id or @name; it returns immediately. A busy recipient gets it after its current run, or during it with steer: true (the default for @ultimate). images forwards screenshots or other images from your conversation, to an agent or to the user. To an agent or the user whose message you owe an answer, it is that answer (with its images and questions) and ends your run.', + 'Send a message to #id or @name; it returns immediately. A busy recipient gets it after its current run, or during it with steer: true (the default for the standing agent). images forwards screenshots or other images from your conversation, to an agent or to the user. To an agent or the user whose message you owe an answer, it is that answer (with its images and questions) and ends your run.', parameters: obj({ to: str(), text: str({ minLength: 1 }), @@ -196,7 +196,7 @@ export default function messages(host: ExtensionHost) { } if (input.to !== 'user') return { output: [{ type: 'text', text: `Message ${id} sent.` }] } - // The message is @ultimate's answer: the run ends here instead of restating it, unless a reply it has read + // The message is the standing agent's answer: the run ends here instead of restating it, unless a reply it has read // is owed. One still queued gets its own turn. const owed = await host .harness() diff --git a/extensions/models/README.md b/extensions/models/README.md index cba32de..44efc29 100644 --- a/extensions/models/README.md +++ b/extensions/models/README.md @@ -1,21 +1,22 @@ # Model selection The `models` service starts a conversation with `start({agent, cwd, ownership?}, context)`. -The `agent` field names a built-in definition or a project overlay. +The `agent` field names a roster entry in `/etc/sausage/config.yaml`. The service stores that name in `models.profile`. `discover(cwd)` exposes the same live definition resolver to subagents. `configure(tx, id, {agent, inheritedTools, excludeTools?, model?, thinking?})` configures an existing child in its creation transaction. It retains the parent's tool scope, explicit overrides, and exclusions for subsequent run boundaries. It applies the definition during creation and before each new run. -Definitions without an explicit model follow their family, then the default family. +Each roster entry names its model and thinking level directly. There are no model families or project overlays. -Each resolution reads `/src/sausage/agents/models.json` and the definition files through `host.fs`. +Each resolution reads `/etc/sausage/config.yaml` through `host.fs`. A file edit applies at the next run boundary without a restart. -The project definitions live under `/.sausage/agents/`. -The existing T37 parser controls validation, overlays, model suffixes, and tool denials. +The global `prompt` precedes the role-specific `prompt` in every agent's system prompt. +A standing conversation follows the current `standing` roster member, even after a rename. The optional `models.pin` service supplies `pin(tx, conversationId)` for an external model override. -Without that provider, the definition or default family selects the model. +Without that provider, the roster entry selects the model. +A conversation without a role uses the standing roster member's model. No login fallback runs. Existing registered models retain their transport. @@ -30,7 +31,9 @@ The extension never reads a credential or registers a direct provider SDK. OpenAI models use pi-ai's Responses transport. Anthropic models use its Messages transport. The catalog endpoint determines each model's base URL. For Anthropic, effort capabilities select adaptive thinking and its advertised effort levels. -Both providers use the existing `llm-proxy` key and usage tag. No provider login or direct endpoint fallback runs. +Both providers read the proxy key and base URL from `/etc/sausage/config.yaml` before each request. +The usage tag remains unchanged. No provider login or direct endpoint fallback runs. +Empty proxy settings do not prevent startup. A model request names the config file if either setting is empty. If the catalog fails or exceeds five seconds, a small table supplies these defaults: @@ -43,7 +46,7 @@ Catalog prices use USD per million tokens, with conversion from `unit_tokens` wh The host uses the first advertised route's quote, including cache reads and cache writes. These costs are estimates, not billing totals. Another proxy route can charge different prices. Unavailable prices remain zero. Catalog changes apply after a host restart. -World family edits still apply at the next run boundary without a restart. -`host/tests/proxy_models.rs` tests the real transports against a local fake proxy. +Roster edits still apply at the next run boundary without a restart. +`host/tests/it/proxy_models.rs` tests the real transports against a local fake proxy. -`host/tests/core_ext.rs` tests these services through the snapshot loader. +`host/tests/it/core_ext.rs` tests these services through the snapshot loader. diff --git a/extensions/models/server.ts b/extensions/models/server.ts index 25dee75..7c5e662 100644 --- a/extensions/models/server.ts +++ b/extensions/models/server.ts @@ -1,32 +1,15 @@ -/** Resolve world families and definitions at each run boundary. All real requests retain the host proxy transport. */ +/** Read the world config at every run boundary. All real requests retain the host proxy transport. */ import { AgentDoc, defineExtension, GenerationTask, hook } from '@earendil-works/pi-durable' -import { definitionRuns, discoverAgents, parseDefinition, parseOverlay, parseFamilies, parseFrontmatter, toolsFor } from '../core/agents.ts' +import { CONFIG, definitionRuns, parseConfig, toolsFor } from '../core/agents.ts' import { ModelsApi, Pin, Profile } from './api.ts' -import { repoRoot } from './files.ts' + export const order = -200 export default function models(host: any) { - const read = async (cwd: string) => { - const families = parseFamilies(await host.fs.read('/src/sausage/agents/models.json')) - const root = await repoRoot(host.fs, cwd) - const files = [] - for (const folder of ['/src/sausage/agents', `${root}/.sausage/agents`]) { - let entries - try { entries = await host.fs.list(folder) } catch (error) { if (error.code !== 'not_found') throw error; entries = [] } - for (const entry of entries) if (entry.kind === 'file' && entry.name.endsWith('.md')) { - const path = `${folder}/${entry.name}` - files.push({path, text:await host.fs.read(path)}) - } - } - const refs = Object.values(families).map(spec => spec.model.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, '')) - // Explicit pins can name a proxy model outside the families. - for (const file of files) { - try { - const parsed = 'addTools' in parseFrontmatter(file.text).frontmatter ? parseOverlay(file.text,file.path).settings : parseDefinition(file.text,file.path) - if (parsed.model) refs.push(parsed.model.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, '')) - } catch { /* discoverAgents records invalid files without replacing valid definitions. */ } - } - const found = discoverAgents(files, '/src/sausage', root, families, refs) - return {families, ...found} + const read = async (_cwd: string) => { + const config = parseConfig(await host.fs.read(CONFIG)) + return {...config, definitions:config.definitions.map((definition: any)=>({...definition, + resident:definition.name === config.standing || definition.resident, + runs:definitionRuns(definition)})), errors:[], replaced:[]} } const register = (ref: any) => { const store = host.models() @@ -42,17 +25,18 @@ export default function models(host: any) { const state = await tx.doc(AgentDoc, id) const profile = await tx.doc(Profile, id) const config = await read(state.cwd ?? '/') + if (profile.standing) profile.agent = config.standing const definition = profile.agent ? config.definitions.find(d => d.name === profile.agent) : undefined if (profile.agent && !definition) throw new Error(`Unknown agent ${profile.agent}: ${JSON.stringify(config.errors)}`) - const selected = definition?.runs ?? definitionRuns({} as any,config.families,Object.values(config.families).map(spec=>spec.model.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, ''))) + const selected = (definition ?? config.definitions.find((d: any)=>d.name === config.standing)).runs const pinned = await host.want(Pin)?.pin(tx, id) const ref = pinned ?? profile.model ?? selected.model register(ref) state.model = ref if (profile.thinking ?? selected.thinking) state.thinkingLevel = profile.thinking ?? selected.thinking else delete state.thinkingLevel + state.instructions = [config.prompt, definition ? `You are @${definition.name}.\n\n${definition.instructions}` : ''].filter(Boolean).join('\n\n') if (definition) { - state.instructions = definition.instructions if (profile.inheritedTools === undefined) profile.inheritedTools = state.tools ?? null const inherited = profile.inheritedTools if (definition.tools || Array.isArray(inherited)) state.tools = toolsFor(definition,inherited ?? []).filter(name=>!profile.excludeTools?.includes(name)) @@ -65,6 +49,7 @@ export default function models(host: any) { configure: async (tx: any, id: number, options: any) => { const profile = await tx.doc(Profile,id) profile.agent = options.agent + profile.standing = options.standing ?? false profile.inheritedTools = options.inheritedTools profile.excludeTools = options.excludeTools ?? [] if (options.model) profile.model = options.model diff --git a/extensions/pause/README.md b/extensions/pause/README.md index 042a780..52816ad 100644 --- a/extensions/pause/README.md +++ b/extensions/pause/README.md @@ -23,4 +23,4 @@ A manual pause always requires Play. The timer operates outside the held scheduler. The stored pause re-arms the timer after restart. -The test module ports all 19 Ultimate pause cases through snapshot-loaded modules. +The test module ports all 19 Standing agent pause cases through snapshot-loaded modules. diff --git a/extensions/pause/api.ts b/extensions/pause/api.ts index 1c3adff..b93a815 100644 --- a/extensions/pause/api.ts +++ b/extensions/pause/api.ts @@ -1,4 +1,4 @@ -/** Pause: whether the user paused this Ultimate, for timers that start work outside the task scheduler. */ +/** Pause: whether the user paused this Standing agent, for timers that start work outside the task scheduler. */ const defineApi = () => (name: string): {name: string; service?: S} => ({name}) export type PauseService = { diff --git a/extensions/pause/refs.ts b/extensions/pause/refs.ts index 638e30a..e0d2928 100644 --- a/extensions/pause/refs.ts +++ b/extensions/pause/refs.ts @@ -1,10 +1,10 @@ -/** Pause in the browser: whether this Ultimate is paused, what still runs, and Pause and Play. Browser-safe. */ +/** Pause in the browser: whether this Standing agent is paused, what still runs, and Pause and Play. Browser-safe. */ const actionRef = (extension: string, name: string) => ({extension, name}) const docRef = (kind: string) => ({kind}) /** - * The rate limit that paused Ultimate: the provider and model that answered with it, the error as Pi recorded it, - * when (ms), and the conversation it first hit. Also the data of the `pause.limit` card in @ultimate's transcript. + * The rate limit that paused Standing agent: the provider and model that answered with it, the error as Pi recorded it, + * when (ms), and the conversation it first hit. Also the data of the `pause.limit` card in the standing agent's transcript. */ export type RateLimit = { provider: string @@ -25,7 +25,7 @@ export type PauseDocState = { limit?: RateLimit /** The user pressed Pause during this pause: it never plays by itself. */ manual?: boolean - /** The user's setting: minutes after a rate-limit pause began that Ultimate presses Play by itself; unset is off. */ + /** The user's setting: minutes after a rate-limit pause began that Standing agent presses Play by itself; unset is off. */ autoPlay?: number } @@ -44,7 +44,7 @@ export type RunningTask = { export type PauseState = { paused: boolean since?: number - /** The rate limit that paused Ultimate, if one did. */ + /** The rate limit that paused Standing agent, if one did. */ limit?: RateLimit /** Minutes after a rate-limit pause began that Play is pressed by itself; unset is off. */ autoPlay?: number @@ -66,7 +66,7 @@ export const PauseAction = actionRef('pause', 'pause') /** User-only: continue. Each run that was mid-turn when paused gets one "Paused for …" note. Returns the state. */ export const PlayAction = actionRef('pause', 'play') /** - * User-only `{ minutes }`: play by itself that many minutes (1 to 1440) after a rate limit paused Ultimate, once per + * User-only `{ minutes }`: play by itself that many minutes (1 to 1440) after a rate limit paused Standing agent, once per * pause; `null` turns it off. A pause the user pressed never plays by itself. Returns the state. */ export const AutoPlayAction = actionRef<{ minutes: number | null }, PauseState>('pause', 'autoPlay') @@ -79,9 +79,9 @@ export type PauseNote = { since: number; until: number; finished?: boolean; auto /** * The `pause.held` entry in a subagent's parent, mid-turn when the subagent hit a rate limit: subagent `child` hit - * `provider`'s limit for `model` at `at` (ms), and Ultimate is paused until Play. + * `provider`'s limit for `model` at `at` (ms), and Standing agent is paused until Play. */ export type HeldNote = { child: number; provider: string; model: string; at: number } -/** The `pause.autoplay` entry in @ultimate's transcript: the rate-limit pause from `since` played by itself at `at`. */ +/** The `pause.autoplay` entry in the standing agent's transcript: the rate-limit pause from `since` played by itself at `at`. */ export type AutoPlayed = { since: number; at: number; minutes: number } diff --git a/extensions/pause/server.ts b/extensions/pause/server.ts index 3e1428d..d253680 100644 --- a/extensions/pause/server.ts +++ b/extensions/pause/server.ts @@ -63,9 +63,9 @@ function serial(host: Pick, work: () => Promise * while paused and execute nothing meanwhile, so they never keep the pause from being safe. */ const PASSIVE: Record = { - 'ultimate.subagent-reporter': ['deliver', 'retry'], - 'ultimate.automation-scheduler': ['sleep'], - 'ultimate.automation-run': ['deliver'], + 'standing.subagent-reporter': ['deliver', 'retry'], + 'standing.automation-scheduler': ['sleep'], + 'standing.automation-run': ['deliver'], 'board.delivery': ['deliver', 'reply'], 'board.route': ['observe'], 'conversations.summary': ['observe'], @@ -213,7 +213,7 @@ function arm(host: Host, doc: PauseDocState) { /** * Play the pause by itself once its time came (`now`, for tests), once: Play ends the pause, and a limit that still - * holds pauses again with a new start and a full grace period. Tells @ultimate with a `pause.autoplay` entry first, + * holds pauses again with a new start and a full grace period. Tells the standing agent with a `pause.autoplay` entry first, * while the pause is still recorded: a crash before Play reopens paused, re-arms the timer, and the entry's request ID * keeps the second announcement from repeating. */ @@ -224,10 +224,10 @@ export async function autoPlay(host: Host, now = Date.now()) { if (at === undefined || now < at) return false const data: AutoPlayed = { since: doc.since!, at: now, minutes: doc.autoPlay! } const harness = host.harness() - const ultimate = (await harness.snapshot(Standing, ROOT_CONVERSATION_ID, context))?.ultimate - if (ultimate !== undefined) + const standing = (await harness.snapshot(Standing, ROOT_CONVERSATION_ID, context))?.['$standing'] + if (standing !== undefined) await ( - await harness.conversation(ultimate, context) + await harness.conversation(standing, context) )?.submit( { type: 'write', @@ -238,7 +238,7 @@ export async function autoPlay(host: Host, now = Date.now()) { model: [ { role: 'user', - content: `Ultimate played by itself ${lasted(now - data.since)} after the rate limit paused it (the user's setting: ${data.minutes} min).`, + content: `Standing agent played by itself ${lasted(now - data.since)} after the rate limit paused it (the user's setting: ${data.minutes} min).`, timestamp: now, }, ], @@ -251,7 +251,7 @@ export async function autoPlay(host: Host, now = Date.now()) { }) } -/** The user's setting: play by itself `minutes` after a rate limit paused Ultimate; `null` turns it off. */ +/** The user's setting: play by itself `minutes` after a rate limit paused Standing agent; `null` turns it off. */ async function setAutoPlay(host: Host, minutes: unknown) { if ( minutes !== null && @@ -268,7 +268,7 @@ async function setAutoPlay(host: Host, minutes: unknown) { } /** - * A model answered with a rate limit: pause, so nothing retries into it, and tell @ultimate with one `pause.limit` + * A model answered with a rate limit: pause, so nothing retries into it, and tell the standing agent with one `pause.limit` * card. Pi has already scheduled that generation's retry; the hold parks it, and every other run at its next step, * until Play. The caller holds the scheduler already, in the commit's publication, before that retry's timer can fire. */ @@ -318,12 +318,12 @@ async function held(host: Host, limit: RateLimit) { /** The `pause.limit` card for the limit that paused the host, once per pause (its request ID is the pause's start). */ async function card(host: Host, doc: PauseDocState) { const harness = host.harness() - const ultimate = (await harness.snapshot(Standing, ROOT_CONVERSATION_ID, context))?.ultimate - if (!doc.paused || !doc.limit || ultimate === undefined) return - // Only kind and data, so Pi appends it at once even while @ultimate's own run is held; the model learns of the limit + const standing = (await harness.snapshot(Standing, ROOT_CONVERSATION_ID, context))?.['$standing'] + if (!doc.paused || !doc.limit || standing === undefined) return + // Only kind and data, so Pi appends it at once even while the standing agent's own run is held; the model learns of the limit // from the note Play leaves on each held run. await ( - await harness.conversation(ultimate, context) + await harness.conversation(standing, context) )?.submit( { type: 'write', @@ -380,7 +380,7 @@ async function play(host: Host, auto = false) { const content = how === 'finished' ? `Paused for ${span} after this run's last answer.` - : `Paused for ${span}; the run continued after ${auto ? 'Ultimate played by itself' : 'Play'}.` + : `Paused for ${span}; the run continued after ${auto ? 'Standing agent played by itself' : 'Play'}.` const conversation = await harness.conversation(id, context) await conversation?.submit( { diff --git a/extensions/plan/README.md b/extensions/plan/README.md index 3b561bd..e1ab45a 100644 --- a/extensions/plan/README.md +++ b/extensions/plan/README.md @@ -1,6 +1,6 @@ # Plan -The `plan` tool maintains a durable epic/task ledger in `ultimate.plan`. +The `plan` tool maintains a durable epic/task ledger in `standing.plan`. Task-owned descendants read their top owner's ledger. Only that owner edits it. Ownerless conversations maintain separate ledgers. @@ -8,7 +8,7 @@ Edits and receipts commit together. Memo namespaces distinguish nested calls tha The tool returns both JSON text and structured content. The compact prompt section excludes completed epics. -The root document `ultimate.plan.tasks` indexes linked child conversations. +The root document `standing.plan.tasks` indexes linked child conversations. A new link or task title change updates the child's metadata title. Other edits preserve a title that the user supplied. diff --git a/extensions/plan/server.ts b/extensions/plan/server.ts index c9eead4..7216323 100644 --- a/extensions/plan/server.ts +++ b/extensions/plan/server.ts @@ -37,7 +37,7 @@ export type Epic = { tasks: Record } export const Plan = defineDoc<{ next: number; epics: Record }>({ - kind: 'ultimate.plan', + kind: 'standing.plan', checkpointWhen: () => false, version: 1, scope: 'conversation', @@ -54,7 +54,7 @@ export type TaskLink = { status: Task['status'] } export const TaskIndex = defineDoc<{ children: Record }>({ - kind: 'ultimate.plan.tasks', + kind: 'standing.plan.tasks', checkpointWhen: () => false, version: 1, scope: 'conversation', @@ -65,7 +65,7 @@ export const TaskIndex = defineDoc<{ children: Record }>({ export const docs = [Plan, TaskIndex] // Commit the receipt with the edit, closing the crash window before api.memo stores the result. const Receipt = defineDoc<{ results: Record }>({ - kind: 'ultimate.plan.receipt', + kind: 'standing.plan.receipt', checkpointWhen: () => false, version: 1, scope: 'task', diff --git a/extensions/prompt/README.md b/extensions/prompt/README.md index df1d0ef..50f1261 100644 --- a/extensions/prompt/README.md +++ b/extensions/prompt/README.md @@ -1,6 +1,12 @@ # System context -The prompt extension supplies `project_context`, `skills`, `tools`, and `cwd` sections. +Every agent receives the top-level `prompt` from `/etc/sausage/config.yaml`, followed by its roster entry's `prompt`. +The models extension reads both prompts again before each run. +An edit applies to an existing conversation at its next run without a host restart. +The default global prompt explains the world, its source, its config, and the harness routes. +Agents can edit that shared guidance through the config. + +The prompt extension supplies only runtime context: `project_context`, `skills`, `tools`, and `cwd` sections. The effective environment cwd takes precedence over the configured agent cwd. Project instructions include each AGENTS.md from the repository root to that cwd, in that order. Outside a repository, the extension reads the cwd's AGENTS.md only. @@ -9,6 +15,6 @@ Skills come from `/src/sausage/skills/*/SKILL.md` and `/.sausage/skills/*/ The prompt lists each skill's name, description, and path. A project skill replaces a built-in skill with the same name. The tools section lists the tools that the resolved agent can use. -No Ultimate build note enters the prompt. -`host/tests/core_ext.rs` tests these sections through the real snapshot loader. +`host/tests/it/core_ext.rs` tests these sections through the real snapshot loader. +It also inspects the actual model request for harness guidance, prompt order, and a live global prompt edit. diff --git a/extensions/subagents/api.ts b/extensions/subagents/api.ts index 44feedd..5e2c143 100644 --- a/extensions/subagents/api.ts +++ b/extensions/subagents/api.ts @@ -38,7 +38,7 @@ export const Subagents = defineDoc<{ } > }>({ - kind: 'ultimate.subagents', + kind: 'standing.subagents', checkpointWhen: () => false, version: 1, scope: 'conversation', @@ -74,7 +74,7 @@ export const Runs = defineDoc>({ * made on the fly has none: `adhoc`, so nothing looks a definition up by its label. */ export const Profile = defineDoc<{ definition?: string; adhoc?: true }>({ - kind: 'ultimate.agent-profile', + kind: 'standing.agent-profile', checkpointWhen: () => false, version: 1, scope: 'conversation', diff --git a/extensions/subagents/children.ts b/extensions/subagents/children.ts index 6c6d94f..d88906e 100644 --- a/extensions/subagents/children.ts +++ b/extensions/subagents/children.ts @@ -26,6 +26,7 @@ export async function configureChild(host: any, tx: any, id: number, options: an await configure(tx, id, childConfiguration(options)) if (options.definition) await host.need(ModelsApi).configure(tx, id, { agent:options.definition.name, + standing:options.standing ?? false, inheritedTools:options.parentAgent.tools.map((tool: any)=>tool.name), excludeTools:options.excludeTools, model:options.model, diff --git a/extensions/subagents/landing.ts b/extensions/subagents/landing.ts index 08da662..97a539e 100644 --- a/extensions/subagents/landing.ts +++ b/extensions/subagents/landing.ts @@ -1,6 +1,6 @@ /** * Where a page opens when no conversation is chosen (a first load, a new chapter, a remembered one that is gone): - * @ultimate's conversation, once the shared state and the standing agents are known; 'create' when @ultimate has no + * the standing agent's conversation, once the shared state and the standing agents are known; 'create' when the standing agent has no * conversation yet, as on a fresh preview. The root is only its history. */ export const landing = ( @@ -9,5 +9,5 @@ export const landing = ( standing: Readonly> | null | undefined, ): number | 'create' | undefined => { if (!loaded || chosen !== undefined || standing === undefined) return undefined - return standing?.ultimate ?? 'create' + return standing?.['$standing'] ?? 'create' } diff --git a/extensions/subagents/refs.ts b/extensions/subagents/refs.ts index 943529e..ce52ea9 100644 --- a/extensions/subagents/refs.ts +++ b/extensions/subagents/refs.ts @@ -3,4 +3,4 @@ import { defineEvent } from '@earendil-works/sausage-events' export const Started = defineEvent<{id:number; agent:string; model?:string; thinking?:string; parent?:number; kind:'child'|'standing'|'branch'}>('subagents.started') export type Run = {model?:string; adhoc?:true} export const RunsDoc = {kind:'subagents.runs'} -export const StandingDoc = {kind:'ultimate.standing-agents'} +export const StandingDoc = {kind:'standing.standing-agents'} diff --git a/extensions/subagents/server.ts b/extensions/subagents/server.ts index 6976617..84f0fd2 100644 --- a/extensions/subagents/server.ts +++ b/extensions/subagents/server.ts @@ -15,7 +15,7 @@ const onCommit = (harness: any, callback: any) => { return () => observation.detach() } const Anchor = defineTask({ - name: 'ultimate.subagent-anchor', + name: 'standing.subagent-anchor', version: 1, initial: () => ({ phase: 'done' }), phases: { @@ -63,7 +63,7 @@ function createReporter() { { phase: 'deliver' } | { phase: 'report'; report?: string; answer?: EntryId }, null >({ - name: 'ultimate.subagent-reporter', + name: 'standing.subagent-reporter', version: 1, initial: (input) => input.answer === undefined @@ -314,15 +314,22 @@ export default function subagents(host: any) { const parentAgent = await root.agent(ctx) return host.harness().commit(async (tx: any) => { const index = await tx.doc(Standing, ROOT_CONVERSATION_ID) - const existing = index[name] && await tx.conversation(index[name]) + const primary = name === found.standing + const key = primary ? '$standing' : name + const existing = index[key] && await tx.conversation(index[key]) const lifecycle = host.want({name:'conversations'}) if (existing) { await lifecycle?.setStanding(tx, existing.id, true) await lifecycle?.setAutomaticSummaries(tx, existing.id, false) - await configureChild(host, tx, existing.id, {definition, parentAgent}) + if (primary) for (const alias of Object.keys(index)) if (alias !== '$standing' && index[alias] === existing.id) delete index[alias] + index[name] = existing.id + const metadata = await tx.doc(host.metadata, existing.id) + if (metadata.label !== name) Object.assign(metadata, {label:name, title:`@${name}`}) + await configureChild(host, tx, existing.id, {definition, parentAgent, standing:primary}) return existing.id } - const child = await createChild(host, tx, {owner: {kind:'ownerless'}, definition, parentAgent, metadata:host.metadata, label:name, title:`@${name}`}) + const child = await createChild(host, tx, {owner: {kind:'ownerless'}, definition, parentAgent, metadata:host.metadata, label:name, title:`@${name}`, standing:primary}) + index[key] = child.id index[name] = child.id await lifecycle?.setStanding(tx, child.id, true) await lifecycle?.setAutomaticSummaries(tx, child.id, false) @@ -428,10 +435,10 @@ export default function subagents(host: any) { const found = await models.discover('/src/sausage') if (!found.errors.length) await host.harness().commit(async (tx: any) => { const index = await tx.doc(Standing, ROOT_CONVERSATION_ID) - for (const name of Object.keys(index)) if (!found.definitions.some((d: any) => d.name === name && d.resident)) { + for (const name of Object.keys(index)) if (name !== '$standing' && !found.definitions.some((d: any) => d.name === name && d.resident)) { const id = index[name] delete index[name] - if (await tx.conversation(id)) { + if (id !== index['$standing'] && await tx.conversation(id)) { delete (await tx.doc(host.metadata, id)).label await host.want({name:'conversations'})?.setStanding(tx, id, false) } diff --git a/extensions/todos/README.md b/extensions/todos/README.md index 9325b3c..3dc54ab 100644 --- a/extensions/todos/README.md +++ b/extensions/todos/README.md @@ -1,15 +1,15 @@ # Todos The root document `todos` stores the world's to-do list. -Each item belongs to `user` or `ultimate`. +Each item belongs to `user` or `standing`. The `todo` tool adds items, completes items, and lists open items by owner. Text must contain 1–300 characters after the tool trims it. The list retains the newest 50 completed items. The exported `mark` helper also reopens items. -Only the standing `ultimate` conversation uses the tool. -The reader uses the existing `ultimate.standing-agents` document contract. +Only the standing `standing` conversation uses the tool. +The reader uses the existing `standing.standing-agents` document contract. Until subagents supplies that document, no conversation qualifies automatically. -This port does not designate the root as `ultimate`. +This port does not designate the root as `standing`. The `beforeInput` hook places a note only when the standing conversation's open list changes. The note and the remembered list commit with the input. diff --git a/extensions/todos/server.ts b/extensions/todos/server.ts index f18caeb..d1e9208 100644 --- a/extensions/todos/server.ts +++ b/extensions/todos/server.ts @@ -1,4 +1,4 @@ -/** The world's root to-do list, its todo tool, and changed-list notes for the standing @ultimate conversation. */ +/** The world's root to-do list, its todo tool, and changed-list notes for the standing conversation. */ import { int, obj, oneOf, opt, str } from '@earendil-works/pi-schema' import { defineDoc, @@ -11,10 +11,10 @@ import { import type { ConversationId, Tx } from '@earendil-works/pi-durable' // Read subagents' standing-agent contract without requiring its extension yet. export const Standing = defineDoc>({ - kind: 'ultimate.standing-agents', checkpointWhen: () => false, version: 1, + kind: 'standing.standing-agents', checkpointWhen: () => false, version: 1, scope: 'conversation', history: 'latest', fork: 'initial', initial: () => ({}), }) -export type Todo = { id: number; text: string; owner: 'user' | 'ultimate'; at: number; done?: number } +export type Todo = { id: number; text: string; owner: 'user' | 'standing'; at: number; done?: number } /** Done to-dos kept; older ones are dropped when another is ticked. */ export const DONE_LIMIT = 50 @@ -29,7 +29,7 @@ export const Todos = defineDoc<{ next: number; items: Todo[] }>({ fork: 'initial', initial: () => ({ next: 1, items: [] }), }) -/** The open list @ultimate last heard, so it hears again only after a change. */ +/** The open list the standing agent last heard, so it hears again only after a change. */ const Seen = defineDoc<{ key?: string }>({ kind: 'todos.seen', checkpointWhen: () => false, @@ -41,14 +41,14 @@ const Seen = defineDoc<{ key?: string }>({ }) export const docs = [Todos] -const OWNERS = ['user', 'ultimate'] as const +const OWNERS = ['user', 'standing'] as const export async function add(tx: Tx, text: unknown, owner: unknown) { if (typeof text !== 'string' || !text.trim()) throw new Error('text must be nonempty') if (text.trim().length > TEXT_CHARS) throw new Error(`text must be at most ${TEXT_CHARS} characters`) if (!OWNERS.includes(owner as Todo['owner'])) - throw new Error("owner must be 'user' or 'ultimate'") + throw new Error("owner must be 'user' or 'standing'") const todos = await tx.doc(Todos, ROOT_CONVERSATION_ID) const todo: Todo = { id: todos.next++, @@ -85,7 +85,7 @@ const line = (todo: Todo) => `- ${todo.id}: ${todo.text}` export function listText(items: readonly Todo[]) { const open = items.filter((item) => item.done === undefined) if (!open.length) return undefined - const mine = open.filter((item) => item.owner === 'ultimate') + const mine = open.filter((item) => item.owner === 'standing') const theirs = open.filter((item) => item.owner === 'user') return [ ...(mine.length ? ['Yours:', ...mine.map(line)] : []), @@ -93,7 +93,7 @@ export function listText(items: readonly Todo[]) { ].join('\n') } -/** @ultimate's note when the open list changed since it last heard it; undefined otherwise. */ +/** the standing agent's note when the open list changed since it last heard it; undefined otherwise. */ export async function noteFor(tx: Tx, conversationId: ConversationId, now: number) { const items = (await tx.doc(Todos, ROOT_CONVERSATION_ID)).items const text = listText(items) @@ -121,7 +121,7 @@ export async function noteFor(tx: Tx, conversationId: ConversationId, now: numbe } const standing = (tx: Tx, id: ConversationId) => - tx.doc(Standing, ROOT_CONVERSATION_ID).then((doc) => doc.ultimate === id) + tx.doc(Standing, ROOT_CONVERSATION_ID).then((doc) => doc['$standing'] === id) export default function todosExtension() { return defineExtension({ @@ -141,11 +141,11 @@ export default function todosExtension() { name: 'todo', deferred: true, description: - "The world's to-dos, owned by you ('ultimate') or the user ('user'): add {text, owner}, done {id}, list. Keep open loops here. Only the standing @ultimate conversation maintains this list.", + "The world's to-dos, owned by you ('standing') or the user ('user'): add {text, owner}, done {id}, list. Keep open loops here. Only the standing conversation maintains this list.", parameters: obj({ action: oneOf(['add', 'done', 'list']), text: opt(str()), - owner: opt(oneOf(['user', 'ultimate'])), + owner: opt(oneOf(['user', 'standing'])), id: opt(int({ minimum: 1 })), }), // Not replay-safe (the default): an interrupted add is never rerun, so it commits at most once. @@ -156,7 +156,7 @@ export default function todosExtension() { // Deferred only hides it: a branch can still find it with tool_search, so the caller is checked here. if (!(await standing(tx, caller))) throw new Error( - 'Only @ultimate keeps the to-dos; ask @ultimate to add one.', + 'Only the standing agent keeps the to-dos; ask the standing agent to add one.', ) if (args.action === 'add') { const todo = await add(tx, args.text, args.owner) diff --git a/extensions/watchdog/README.md b/extensions/watchdog/README.md index f81e45b..6f2a3ba 100644 --- a/extensions/watchdog/README.md +++ b/extensions/watchdog/README.md @@ -6,13 +6,13 @@ A temporary provider failure creates a durable `watchdog.failure` task. The task A failed continuation does not receive another retry. Permanent errors report immediately. If another run remains active at the deadline, watchdog does not submit a continuation. -Reports use the messages service with a stable request ID. Owned children report to their owner. Other conversations report to @ultimate. -A failure of @ultimate itself produces a notice instead. The service retains the latest 20 reported failures. +Reports use the messages service with a stable request ID. Owned children report to their owner. Other conversations report to the standing agent. +A failure of the standing agent itself produces a notice instead. The service retains the latest 20 reported failures. Receipts and a high-water mark prevent repeated recovery. Fresh installation excludes historical failures. On reopen, watchdog recovers failures that its observer missed. Retry inputs also use stable request IDs. -Before @ultimate receives an input, watchdog can add an idle-branch note. It does not modify the system prompt. +Before the standing agent receives an input, watchdog can add an idle-branch note. It does not modify the system prompt. The note excludes active branches, concluded branches, user questions, and queued landings when workspaces is available. It waits 30 minutes, or two hours while a branch awaits an agent reply. It repeats only when the branch IDs change. diff --git a/extensions/watchdog/idle.ts b/extensions/watchdog/idle.ts index 5f65a8d..6fe67cf 100644 --- a/extensions/watchdog/idle.ts +++ b/extensions/watchdog/idle.ts @@ -58,7 +58,7 @@ export async function idleNote( return false } const idle = [] - // Branches are ownerless, so subagents are skipped before any document read: this runs before every @ultimate input. + // Branches are ownerless, so subagents are skipped before any document read: this runs before every the standing agent input. for (const conversation of conversations) { if (conversation.owner || excluded.has(conversation.id)) continue if (!(await tx.doc(Branch, conversation.id)).branch) continue diff --git a/extensions/watchdog/retry.ts b/extensions/watchdog/retry.ts index 0e8ec61..31075be 100644 --- a/extensions/watchdog/retry.ts +++ b/extensions/watchdog/retry.ts @@ -128,7 +128,7 @@ import type { AssistantMessage } from '@earendil-works/pi-ai' /** * Whether a model error is a rate limit Pi retries: HTTP 429, "rate limit", "too many requests". Retrying sooner only - * hits the limit again, so Ultimate pauses until the user presses Play, and the held run continues through Pi's retry. + * hits the limit again, so Standing agent pauses until the user presses Play, and the held run continues through Pi's retry. * Quota, usage-limit and billing errors are on Pi's no-retry list: they end the run at once and fail as usual. * Overloaded servers (529) are the provider's capacity, not the account's limit. */ diff --git a/extensions/watchdog/server.ts b/extensions/watchdog/server.ts index 2df95d4..59d9728 100644 --- a/extensions/watchdog/server.ts +++ b/extensions/watchdog/server.ts @@ -310,10 +310,10 @@ export default function watchdog(host: ExtensionHost) { ) return const child = (await tx.conversation(task.conversationId))! - const ultimate = (await tx.doc(Standing, ROOT_CONVERSATION_ID)).ultimate - const recipient = child.owner?.conversationId ?? ultimate + const standing = (await tx.doc(Standing, ROOT_CONVERSATION_ID))['$standing'] + const recipient = child.owner?.conversationId ?? standing if (recipient === undefined) - throw new Error('Watchdog needs @ultimate to report a failed run') + throw new Error('Watchdog needs the standing agent to report a failed run') if (task.state.status !== 'terminal' || task.state.outcome.status !== 'failed') return const error = task.state.outcome.error.message const { hint, temporary } = diagnose(error, info.assistant) @@ -412,7 +412,7 @@ export default function watchdog(host: ExtensionHost) { hooks: [ hook(GenerationTask, { beforeInput: async (_input, { tx, conversationId }) => - (await tx.doc(Standing, ROOT_CONVERSATION_ID)).ultimate === conversationId + (await tx.doc(Standing, ROOT_CONVERSATION_ID))['$standing'] === conversationId ? idleNote(tx, host, conversationId, Date.now()) : undefined, }), diff --git a/extensions/workspaces/api.ts b/extensions/workspaces/api.ts index bb9c9f6..08d8049 100644 --- a/extensions/workspaces/api.ts +++ b/extensions/workspaces/api.ts @@ -4,7 +4,7 @@ import { defineEvent } from '@earendil-works/sausage-events' export type Workspace = {source:string;target:string;path:string;branch:string;base?:string;state:'preparing'|'ready'|'failed'|'removed';preparation?:number;error?:string;landed?:string} export type Submission = {id:string;conversationId:number;source:string;target:string;tip:string;at:number;divergence:string;title:string;conversations:string[];prepared?:{base:string;sha:string};landed?:{base:string;sha:string;commits:{sha:string;subject:string}[];paths:string[]};outcome?:any} export const Workspaces = defineDoc<{items:Record;queue:Submission[];landers:Record;landerConversations:Record;results:Record}>({ - kind:'ultimate.workspaces',version:1,scope:'conversation',history:'latest',fork:'initial',checkpointWhen:()=>false, + kind:'standing.workspaces',version:1,scope:'conversation',history:'latest',fork:'initial',checkpointWhen:()=>false, initial:()=>({items:{},queue:[],landers:{},landerConversations:{},results:{}}), }) export const WorkspacesApi = {name:'workspaces'} diff --git a/host/js/README.md b/host/js/README.md index b9d5c6d..d7340b6 100644 --- a/host/js/README.md +++ b/host/js/README.md @@ -37,7 +37,7 @@ CARGO_TARGET_DIR=target/harness nix develop -c cargo test -p sausage --test harn The lock file pins npm dependencies. The bundle command requires Nushell, GNU patch, and npm. It applies `patches/pi-durable-1.5.0.patch` before esbuild runs. -This is Ultimate's patch at `7ec0b4f`, without the Node execution environment hunks (D65). +This is Standing agent's patch at `7ec0b4f`, without the Node execution environment hunks (D65). The patch adds transactional `beforeInput`, input markers, scheduler hold/release, and the failed-run boundary fix. The step verifies an existing application before another bundle build. A mismatched or partially applied patch fails the command. `npm ci` restores the unpatched dependency. The next bundle command applies the patch again. @@ -85,5 +85,5 @@ The signal client sends `Input::Stop`. The harness closes its watches, credentia The host then stops its process services and HTTP listener. Console output still streams assistant messages, without replay of the historical transcript. -`harness_foundation.rs` runs the three Ultimate input tests and the scheduler phase-boundary test through bundled V8 modules. +`harness_foundation.rs` runs the three Standing agent input tests and the scheduler phase-boundary test through bundled V8 modules. It also tests the channel with closed stdin, CLI EOF and SIGTERM, submission scans, and the patched bundle hooks. diff --git a/host/js/automations-pause-cases.ts b/host/js/automations-pause-cases.ts index 9aad2cb..9971480 100644 --- a/host/js/automations-pause-cases.ts +++ b/host/js/automations-pause-cases.ts @@ -1,4 +1,4 @@ -/** All 19 Ultimate pause cases, executed against world snapshot modules. */ +/** All 19 Standing agent pause cases, executed against world snapshot modules. */ import {expect,it,until,setImmediate} from "./automations-test-support"; import {fixture} from "./automations-pause-fixture"; import {BACKGROUND_CONTEXT as context} from "@earendil-works/chord/context"; @@ -245,9 +245,9 @@ it('pauses on the first rate-limited answer: the run waits in its retry, fails n }, ]) const { root, harness } = await f.open() - const ultimate = await harness.createConversation({ ownership: { kind: 'ownerless' } }, context) + const standing = await harness.createConversation({ ownership: { kind: 'ownerless' } }, context) await harness.commit(async (tx) => { - ;(await tx.doc(Standing, ROOT_CONVERSATION_ID)).ultimate = ultimate.id + ;(await tx.doc(Standing, ROOT_CONVERSATION_ID))['$standing'] = standing.id }, context) const submission = await root.submit({ type: 'input', content: 'go' }, context) await until(async () => (await f.action('state')).limit !== undefined) @@ -263,7 +263,7 @@ it('pauses on the first rate-limited answer: the run waits in its retry, fails n expect(generation.record.state.status).not.toBe('terminal') expect((await harness.snapshot(LiveDoc, root.id, context))?.run).toBeDefined() const cards = async () => - (await ultimate.context(context)).entries.filter((entry) => entry.kind === 'pause.limit') + (await standing.context(context)).entries.filter((entry) => entry.kind === 'pause.limit') await until(async () => (await cards()).length === 1) expect((await cards())[0].data).toMatchObject({ error: limit, conversationId: root.id }) @@ -420,9 +420,9 @@ it('plays a rate-limit pause by itself once, N minutes in, only when the user sw }, ]) const { root, harness } = await f.open() - const ultimate = await harness.createConversation({ ownership: { kind: 'ownerless' } }, context) + const standing = await harness.createConversation({ ownership: { kind: 'ownerless' } }, context) await harness.commit(async (tx) => { - ;(await tx.doc(Standing, ROOT_CONVERSATION_ID)).ultimate = ultimate.id + ;(await tx.doc(Standing, ROOT_CONVERSATION_ID))['$standing'] = standing.id }, context) const submission = await root.submit({ type: 'input', content: 'go' }, context) await until(async () => (await f.action('state')).limit !== undefined) @@ -443,14 +443,14 @@ it('plays a rate-limit pause by itself once, N minutes in, only when the user sw expect(responses).toBe(2) // Once: the pause is over, so a second due timer finds nothing to play. expect(await f.autoPlay(since! + 31 * 60_000)).toBe(false) - const played = (await ultimate.context(context)).entries.filter( + const played = (await standing.context(context)).entries.filter( (entry) => entry.kind === 'pause.autoplay', ) expect(played).toHaveLength(1) expect(played[0].data).toMatchObject({ since, at: since! + 30 * 60_000, minutes: 30 }) const notes = (await root.context(context)).entries.filter((entry) => entry.kind === 'pause.note') expect(notes[0].data).toMatchObject({ auto: true }) - expect(notes[0].model?.[0]?.content).toMatch(/continued after Ultimate played by itself\.$/) + expect(notes[0].model?.[0]?.content).toMatch(/continued after Standing agent played by itself\.$/) // The setting stays for the next limit. expect((await f.action('state')).autoPlay).toBe(30) }) @@ -495,7 +495,7 @@ const at = (kind: string, phase: string) => ({ kind, state: { checkpoint: { phas it('treats message deliveries and routes as passive waiters', () => { expect(passive(at('board.delivery', 'deliver'))).toBe(true) expect(passive(at('board.delivery', 'reply'))).toBe(true) - expect(passive(at('ultimate.subagent-reporter', 'deliver'))).toBe(true) + expect(passive(at('standing.subagent-reporter', 'deliver'))).toBe(true) expect(passive(at('board.route', 'observe'))).toBe(true) expect(passive(at('conversations.summary', 'generate'))).toBe(false) }) diff --git a/host/js/automations-pause-fixture.ts b/host/js/automations-pause-fixture.ts index 5533dd6..4b03478 100644 --- a/host/js/automations-pause-fixture.ts +++ b/host/js/automations-pause-fixture.ts @@ -1,4 +1,4 @@ -/** Pause cases use snapshot modules and isolated durable storage, as Ultimate's fixture does. */ +/** Pause cases use snapshot modules and isolated durable storage, as Standing agent's fixture does. */ import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context' import { obj } from '@earendil-works/pi-schema' import { createModels } from '@earendil-works/pi-ai/models' diff --git a/host/js/automations-schedule-cases.ts b/host/js/automations-schedule-cases.ts index 272a4ad..fe0fc32 100644 --- a/host/js/automations-schedule-cases.ts +++ b/host/js/automations-schedule-cases.ts @@ -1,4 +1,4 @@ -/** The five Ultimate calendar cases execute inside deno_core's V8. */ +/** The five Standing agent calendar cases execute inside deno_core's V8. */ import {describe, expect, it} from "./automations-test-support"; const {describeSchedule,nextAt,parseSchedule}=await import(`${globalThis.automationBase}/automations/schedule.ts`); const time = Date.parse('2026-01-05T08:00:00Z') diff --git a/host/js/automations-test-bundle.js b/host/js/automations-test-bundle.js index 4222933..e59ee77 100644 --- a/host/js/automations-test-bundle.js +++ b/host/js/automations-test-bundle.js @@ -41,10 +41,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -106,8 +106,8 @@ var init_memory = __esm({ }); // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -359,7 +359,7 @@ var init_event_stream = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -376,7 +376,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1243,11 +1243,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1259,14 +1259,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -2294,8 +2294,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -3375,11 +3375,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3393,8 +3393,8 @@ function map(value2, options = {}) { function bytes(options = {}) { return { type: "bytes", ...options }; } -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3421,8 +3421,8 @@ var init_builders = __esm({ "node_modules/@earendil-works/pi-schema/dist/builders.js"() { Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; } @@ -3490,8 +3490,8 @@ var init_resolver = __esm({ if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3567,10 +3567,10 @@ var init_resolver = __esm({ for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3580,12 +3580,12 @@ var init_resolver = __esm({ } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base, fragment) { let node = root2; @@ -3647,17 +3647,17 @@ var init_shared = __esm({ }); // node_modules/@earendil-works/pi-schema/dist/coerce.js -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next2 = map2(items[i], i); + const next2 = map3(items[i], i); if (next2 === items[i]) continue; out ??= items.slice(); @@ -3751,11 +3751,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -3839,9 +3839,9 @@ var init_coerce = __esm({ * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3903,26 +3903,26 @@ var init_coerce = __esm({ // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next2) => { + const set2 = (key, next2) => { if (next2 === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3937,7 +3937,7 @@ var init_coerce = __esm({ delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3946,10 +3946,10 @@ var init_coerce = __esm({ if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -4055,8 +4055,8 @@ var init_coerce = __esm({ return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -4069,7 +4069,7 @@ var init_coerce = __esm({ if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -4079,11 +4079,11 @@ var init_coerce = __esm({ let matched = Object.hasOwn(properties, key); if (matched) next2 = this.convert(properties[key], base, next2); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next2 = this.convert(schema, base, next2); + next2 = this.convert(schema4, base, next2); } if (!matched && additional !== void 0) next2 = this.convert(additional, base, next2); @@ -4097,19 +4097,19 @@ var init_coerce = __esm({ // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next2 = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next2 = this.coerceTypes(next2, member, b); - if (Array.isArray(schema.anyOf)) - next2 = this.coerceUnion(next2, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next2 = this.coerceUnion(next2, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next2 = this.coerceUnion(next2, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next2 = this.coerceUnion(next2, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next2, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -4121,9 +4121,9 @@ var init_coerce = __esm({ } } if (types.includes("object") && isPlainObject(next2)) - next2 = this.coerceProperties(next2, schema, b); + next2 = this.coerceProperties(next2, schema4, b); if (types.includes("array") && Array.isArray(next2)) - next2 = this.coerceItems(next2, schema, b); + next2 = this.coerceItems(next2, schema4, b); return next2; } coerceUnion(value2, branches, base) { @@ -4137,12 +4137,12 @@ var init_coerce = __esm({ } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next2) => { + const set2 = (key, next2) => { if (next2 === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -4150,7 +4150,7 @@ var init_coerce = __esm({ }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -4158,16 +4158,16 @@ var init_coerce = __esm({ if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } @@ -4474,9 +4474,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4818,9 +4818,9 @@ var init_compiler = __esm({ scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4886,9 +4886,9 @@ var init_compiler = __esm({ parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4899,7 +4899,7 @@ var init_compiler = __esm({ const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5313,9 +5313,9 @@ var init_explain = __esm({ * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5642,22 +5642,22 @@ var init_explain = __esm({ }); // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } var NO_OPTIONS, Validator, CoercingValidator; @@ -5673,9 +5673,9 @@ var init_validator = __esm({ schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5821,34 +5821,34 @@ function hash64(text) { function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5865,12 +5865,12 @@ function cloneData(value2) { copy2[key] = cloneData(item); return copy2; } -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5879,21 +5879,21 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5901,42 +5901,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5944,7 +5944,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5953,16 +5953,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5975,28 +5975,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -6113,7 +6113,7 @@ var init_schema = __esm({ "node_modules/@earendil-works/chord/dist/schema.js"() { init_dist2(); init_errors(); - asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; + asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; validators = /* @__PURE__ */ new WeakMap(); isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); @@ -6134,7 +6134,7 @@ var init_schema = __esm({ "minProperties", "maxProperties" ]; - typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; + typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -6162,7 +6162,7 @@ var init_schema = __esm({ "writeOnly", "deprecated" ]); - withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); + withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); } }); @@ -6229,8 +6229,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9870,15 +9870,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -9964,10 +9964,10 @@ var init_cell = __esm({ validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9984,11 +9984,11 @@ var init_cell = __esm({ * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -10052,8 +10052,8 @@ var init_cell = __esm({ * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -10250,18 +10250,18 @@ function notifyStatus(listeners, status, error, report2) { }); } function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -10627,8 +10627,8 @@ var init_object = __esm({ const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -11099,15 +11099,15 @@ var init_object = __esm({ } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11368,8 +11368,8 @@ var init_object = __esm({ throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11480,16 +11480,16 @@ var init_object = __esm({ this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11518,13 +11518,13 @@ var init_object = __esm({ return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11533,7 +11533,7 @@ var init_object = __esm({ const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11541,7 +11541,7 @@ var init_object = __esm({ this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11645,15 +11645,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -12027,17 +12027,17 @@ var init_reload = __esm({ for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -12209,11 +12209,11 @@ var init_reload = __esm({ } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -14155,10 +14155,10 @@ var init_remote = __esm({ removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -14185,12 +14185,12 @@ var init_remote = __esm({ view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14469,8 +14469,8 @@ var init_remote = __esm({ if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14970,11 +14970,11 @@ var init_host = __esm({ * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -15222,15 +15222,15 @@ var init_host = __esm({ table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16807,19 +16807,19 @@ var init_cached_storage = __esm({ }); // node_modules/@earendil-works/pi-durable/dist/session/conversation-tails.js -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17750,14 +17750,14 @@ var init_transaction = __esm({ this.#writes.splice(at2, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -18148,8 +18148,8 @@ var init_writer = __esm({ } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -18182,8 +18182,8 @@ var init_writer = __esm({ failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -18201,7 +18201,7 @@ var init_writer = __esm({ try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -19171,7 +19171,7 @@ var init_session = __esm({ writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -19181,15 +19181,15 @@ var init_session = __esm({ * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -19200,7 +19200,7 @@ var init_session = __esm({ * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -19213,7 +19213,7 @@ var init_session = __esm({ continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -19282,7 +19282,7 @@ var init_session = __esm({ const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -19290,7 +19290,7 @@ var init_session = __esm({ hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -19345,7 +19345,7 @@ var init_session = __esm({ * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -19373,9 +19373,9 @@ var init_session = __esm({ const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19879,7 +19879,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19887,27 +19887,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20560,7 +20560,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call2, timestamp) { +function missingResult(call2, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call2.id, @@ -20568,7 +20568,7 @@ function missingResult(call2, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } var SCAN_PAGE_SIZE2, EXCLUDED_STOP_REASONS, MISSING_RESULT_TEXT, deeplyFrozen; @@ -21026,21 +21026,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -21082,14 +21082,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -21118,9 +21118,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -21349,12 +21349,12 @@ var init_util = __esm({ if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -21368,16 +21368,16 @@ var init_util = __esm({ return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -21454,20 +21454,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -25067,13 +25067,13 @@ var init_formats = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/utils/validation.js -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -25591,18 +25591,18 @@ async function afterHarnessResult(runtime, input, call2, tool, result, truncatio return { ...rest, ...value2, output: bounded.content, diagnostics: [...rest.diagnostics ?? [], ...harness2] }; } function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25780,7 +25780,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call2, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25794,7 +25794,7 @@ async function appendToolResult(tx, conversationId, call2, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call2.name, result.usage); @@ -29005,16 +29005,16 @@ var init_memory2 = __esm({ seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -29022,14 +29022,14 @@ var init_memory2 = __esm({ this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -29067,7 +29067,7 @@ var init_memory2 = __esm({ } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -29085,7 +29085,7 @@ var init_memory2 = __esm({ case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -29155,9 +29155,9 @@ var init_memory2 = __esm({ break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -29500,16 +29500,16 @@ var init_memory2 = __esm({ throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions2, seq) { + applyDocumentActions(actions2, seq2) { for (const [id, action] of actions2) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -29527,14 +29527,14 @@ var init_memory2 = __esm({ insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -29740,8 +29740,8 @@ var init_schema3 = __esm({ }); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -29845,8 +29845,8 @@ function createSqliteMigrations(schema) { { version: 2, statements: sleepingStatus } ]; } -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } var SQLITE_MIGRATIONS, CURRENT_SQLITE_SCHEMA_VERSION; var init_migrations2 = __esm({ @@ -29955,20 +29955,20 @@ var init_storage = __esm({ closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -30004,9 +30004,9 @@ var init_storage = __esm({ refused = { error }; break; } - const seq = seqFromNumber(next2++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next2++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -30014,8 +30014,8 @@ var init_storage = __esm({ } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -30033,10 +30033,10 @@ var init_storage = __esm({ await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -30472,7 +30472,7 @@ var init_storage = __esm({ LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -30480,7 +30480,7 @@ var init_storage = __esm({ break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -30525,21 +30525,21 @@ var init_storage = __esm({ } } } - async applyDocumentActions(executor, actions2, seq) { + async applyDocumentActions(executor, actions2, seq2) { for (const [id, action] of actions2) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -30549,12 +30549,12 @@ var init_storage = __esm({ await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -30624,6 +30624,7212 @@ var init_sqlite3 = __esm({ } }); +// node_modules/yaml/browser/dist/nodes/identity.js +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var ALIAS, DOC, MAP, PAIR, SCALAR, SEQ, NODE_TYPE, isAlias, isDocument, isMap, isPair, isScalar, isSeq, hasAnchor; +var init_identity2 = __esm({ + "node_modules/yaml/browser/dist/nodes/identity.js"() { + ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); + DOC = /* @__PURE__ */ Symbol.for("yaml.document"); + MAP = /* @__PURE__ */ Symbol.for("yaml.map"); + PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); + SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); + SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); + NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); + isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; + isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; + isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; + isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; + isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; + isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; + hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + } +}); + +// node_modules/yaml/browser/dist/visit.js +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} +var BREAK, SKIP, REMOVE; +var init_visit = __esm({ + "node_modules/yaml/browser/dist/visit.js"() { + init_identity2(); + BREAK = /* @__PURE__ */ Symbol("break visit"); + SKIP = /* @__PURE__ */ Symbol("skip children"); + REMOVE = /* @__PURE__ */ Symbol("remove node"); + visit.BREAK = BREAK; + visit.SKIP = SKIP; + visit.REMOVE = REMOVE; + visitAsync.BREAK = BREAK; + visitAsync.SKIP = SKIP; + visitAsync.REMOVE = REMOVE; + } +}); + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars, escapeTagName, Directives; +var init_directives = __esm({ + "node_modules/yaml/browser/dist/doc/directives.js"() { + init_identity2(); + init_visit(); + escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" + }; + escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); + Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } + }; + Directives.defaultYaml = { explicit: false, version: "1.2" }; + Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + } +}); + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root2) { + const anchors = /* @__PURE__ */ new Set(); + visit(root2, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} +var init_anchors = __esm({ + "node_modules/yaml/browser/dist/doc/anchors.js"() { + init_identity2(); + init_visit(); + } +}); + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} +var init_applyReviver = __esm({ + "node_modules/yaml/browser/dist/doc/applyReviver.js"() { + } +}); + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} +var init_toJS = __esm({ + "node_modules/yaml/browser/dist/nodes/toJS.js"() { + init_identity2(); + } +}); + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase; +var init_Node = __esm({ + "node_modules/yaml/browser/dist/nodes/Node.js"() { + init_applyReviver(); + init_identity2(); + init_toJS(); + NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + }; + } +}); + +// node_modules/yaml/browser/dist/nodes/Alias.js +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} +var Alias; +var init_Alias = __esm({ + "node_modules/yaml/browser/dist/nodes/Alias.js"() { + init_anchors(); + init_visit(); + init_identity2(); + init_Node(); + init_toJS(); + Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } + }; + } +}); + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue, Scalar; +var init_Scalar = __esm({ + "node_modules/yaml/browser/dist/nodes/Scalar.js"() { + init_identity2(); + init_Node(); + init_toJS(); + isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; + Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } + }; + Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; + Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; + Scalar.PLAIN = "PLAIN"; + Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; + Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + } +}); + +// node_modules/yaml/browser/dist/doc/createNode.js +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} +var defaultTagPrefix; +var init_createNode = __esm({ + "node_modules/yaml/browser/dist/doc/createNode.js"() { + init_Alias(); + init_identity2(); + init_Scalar(); + defaultTagPrefix = "tag:yaml.org,2002:"; + } +}); + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath, Collection; +var init_Collection = __esm({ + "node_modules/yaml/browser/dist/nodes/Collection.js"() { + init_createNode(); + init_identity2(); + init_Node(); + isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; + Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it2) => isNode(it2) || isPair(it2) ? it2.clone(schema4) : it2); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + }; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var stringifyComment, lineComment; +var init_stringifyComment = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyComment.js"() { + stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); + lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + } +}); + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next2 = text[i + 1]; + if (next2 && next2 !== " " && next2 !== "\n" && next2 !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} +var FOLD_FLOW, FOLD_BLOCK, FOLD_QUOTED; +var init_foldFlowLines = __esm({ + "node_modules/yaml/browser/dist/stringify/foldFlowLines.js"() { + FOLD_FLOW = "flow"; + FOLD_BLOCK = "block"; + FOLD_QUOTED = "quoted"; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit2 = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit2) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit2) + return true; + start = i + 1; + if (strLen - start <= limit2) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +function blockString({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + const { blockQuote, commentString, lineWidth } = ctx.options; + if (!blockQuote || /\n[\t ]+$/.test(value2)) { + return quotedString(value2, ctx); + } + const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value2) ? " " : ""); + const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value2, lineWidth, indent.length); + if (!value2) + return literal ? "|\n" : ">\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} +var getFoldOptions, containsDocumentMarker, blockEndNewlines; +var init_stringifyString = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyString.js"() { + init_Scalar(); + init_foldFlowLines(); + getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth + }); + containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); + try { + blockEndNewlines = new RegExp("(^|(? t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} +var init_stringify = __esm({ + "node_modules/yaml/browser/dist/stringify/stringify.js"() { + init_anchors(); + init_identity2(); + init_stringifyComment(); + init_stringifyString(); + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} +var init_stringifyPair = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyPair.js"() { + init_identity2(); + init_Scalar(); + init_stringify(); + init_stringifyComment(); + } +}); + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} +var init_log = __esm({ + "node_modules/yaml/browser/dist/log.js"() { + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it2 of source.items) + mergeValue(ctx, map3, it2); + else if (Array.isArray(source)) + for (const it2 of source) + mergeValue(ctx, map3, it2); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} +var MERGE_KEY, merge3, isMergeKey; +var init_merge = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js"() { + init_identity2(); + init_Scalar(); + MERGE_KEY = "<<"; + merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY + }; + isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); + } +}); + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} +var init_addPairToJSMap = __esm({ + "node_modules/yaml/browser/dist/nodes/addPairToJSMap.js"() { + init_log(); + init_merge(); + init_stringify(); + init_identity2(); + init_toJS(); + } +}); + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair; +var init_Pair = __esm({ + "node_modules/yaml/browser/dist/nodes/Pair.js"() { + init_createNode(); + init_stringifyPair(); + init_addPairToJSMap(); + init_identity2(); + Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } + }; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} +var init_stringifyCollection = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyCollection.js"() { + init_identity2(); + init_stringify(); + init_stringifyComment(); + } +}); + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it2 of items) { + if (isPair(it2)) { + if (it2.key === key || it2.key === k) + return it2; + if (isScalar(it2.key) && it2.key.value === k) + return it2; + } + } + return void 0; +} +var YAMLMap; +var init_YAMLMap = __esm({ + "node_modules/yaml/browser/dist/nodes/YAMLMap.js"() { + init_stringifyCollection(); + init_addPairToJSMap(); + init_Collection(); + init_identity2(); + init_Pair(); + init_Scalar(); + YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it2 = findPair(this.items, key); + if (!it2) + return false; + const del = this.items.splice(this.items.indexOf(it2), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it2 = findPair(this.items, key); + const node = it2?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2; +var init_map = __esm({ + "node_modules/yaml/browser/dist/schema/common/map.js"() { + init_identity2(); + init_YAMLMap(); + map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) + }; + } +}); + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} +var YAMLSeq; +var init_YAMLSeq = __esm({ + "node_modules/yaml/browser/dist/nodes/YAMLSeq.js"() { + init_createNode(); + init_stringifyCollection(); + init_Collection(); + init_identity2(); + init_Scalar(); + init_toJS(); + YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it2 = this.items[idx]; + return !keepScalar && isScalar(it2) ? it2.value : it2; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it2 of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it2 : String(i++); + it2 = replacer.call(obj2, key, it2); + } + seq2.items.push(createNode2(it2, void 0, ctx)); + } + } + return seq2; + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq; +var init_seq = __esm({ + "node_modules/yaml/browser/dist/schema/common/seq.js"() { + init_identity2(); + init_YAMLSeq(); + seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) + }; + } +}); + +// node_modules/yaml/browser/dist/schema/common/string.js +var string; +var init_string = __esm({ + "node_modules/yaml/browser/dist/schema/common/string.js"() { + init_stringifyString(); + string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag; +var init_null = __esm({ + "node_modules/yaml/browser/dist/schema/common/null.js"() { + init_Scalar(); + nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr + }; + } +}); + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag; +var init_bool = __esm({ + "node_modules/yaml/browser/dist/schema/core/bool.js"() { + init_Scalar(); + boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } + }; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} +var init_stringifyNumber = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyNumber.js"() { + } +}); + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN, floatExp, float; +var init_float = __esm({ + "node_modules/yaml/browser/dist/schema/core/float.js"() { + init_Scalar(); + init_stringifyNumber(); + floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber + }; + floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } + }; + float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber + }; + } +}); + +// node_modules/yaml/browser/dist/schema/core/int.js +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intIdentify, intResolve, intOct, int2, intHex; +var init_int = __esm({ + "node_modules/yaml/browser/dist/schema/core/int.js"() { + init_stringifyNumber(); + intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); + intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); + intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") + }; + int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber + }; + intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") + }; + } +}); + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema; +var init_schema4 = __esm({ + "node_modules/yaml/browser/dist/schema/core/schema.js"() { + init_map(); + init_null(); + init_seq(); + init_string(); + init_bool(); + init_float(); + init_int(); + schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float + ]; + } +}); + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON, jsonScalars, jsonError, schema2; +var init_schema5 = __esm({ + "node_modules/yaml/browser/dist/schema/json/schema.js"() { + init_Scalar(); + init_map(); + init_seq(); + stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); + jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } + ]; + jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } + }; + schema2 = [map2, seq].concat(jsonScalars, jsonError); + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary; +var init_binary = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js"() { + init_Scalar(); + init_stringifyString(); + binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it2 of iterable) { + if (typeof replacer === "function") + it2 = replacer.call(iterable, String(i++), it2); + let key, value2; + if (Array.isArray(it2)) { + if (it2.length === 2) { + key = it2[0]; + value2 = it2[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it2}`); + } else if (it2 && it2 instanceof Object) { + const keys = Object.keys(it2); + if (keys.length === 1) { + key = keys[0]; + value2 = it2[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it2; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs; +var init_pairs = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js"() { + init_identity2(); + init_Pair(); + init_Scalar(); + init_YAMLSeq(); + pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap, omap; +var init_omap = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js"() { + init_identity2(); + init_toJS(); + init_YAMLMap(); + init_YAMLSeq(); + init_pairs(); + YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } + }; + YAMLOMap.tag = "tag:yaml.org,2002:omap"; + omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag, falseTag; +var init_bool2 = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js"() { + init_Scalar(); + trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify + }; + falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2, floatExp2, float2; +var init_float2 = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/float.js"() { + init_Scalar(); + init_stringifyNumber(); + floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber + }; + floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } + }; + float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intIdentify3, intBin, intOct2, int3, intHex2; +var init_int2 = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/int.js"() { + init_stringifyNumber(); + intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); + intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") + }; + intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") + }; + int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber + }; + intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet, set; +var init_set = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/set.js"() { + init_identity2(); + init_Pair(); + init_YAMLMap(); + YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } + }; + YAMLSet.tag = "tag:yaml.org,2002:set"; + set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime, floatTime, timestamp; +var init_timestamp = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js"() { + init_stringifyNumber(); + intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal + }; + floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal + }; + timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3; +var init_schema6 = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js"() { + init_map(); + init_null(); + init_seq(); + init_string(); + init_binary(); + init_bool2(); + init_float2(); + init_int2(); + init_merge(); + init_omap(); + init_pairs(); + init_set(); + init_timestamp(); + schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp + ]; + } +}); + +// node_modules/yaml/browser/dist/schema/tags.js +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} +var schemas, tagsByName, coreKnownTags; +var init_tags = __esm({ + "node_modules/yaml/browser/dist/schema/tags.js"() { + init_map(); + init_null(); + init_seq(); + init_string(); + init_bool(); + init_float(); + init_int(); + init_schema4(); + init_schema5(); + init_binary(); + init_merge(); + init_omap(); + init_pairs(); + init_schema6(); + init_set(); + init_timestamp(); + schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] + ]); + tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp + }; + coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp + }; + } +}); + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey, Schema; +var init_Schema = __esm({ + "node_modules/yaml/browser/dist/schema/Schema.js"() { + init_identity2(); + init_map(); + init_seq(); + init_string(); + init_tags(); + sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } + }; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} +var init_stringifyDocument = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyDocument.js"() { + init_identity2(); + init_stringify(); + init_stringifyComment(); + } +}); + +// node_modules/yaml/browser/dist/doc/Document.js +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} +var Document; +var init_Document = __esm({ + "node_modules/yaml/browser/dist/doc/Document.js"() { + init_Alias(); + init_Collection(); + init_identity2(); + init_Pair(); + init_toJS(); + init_Schema(); + init_stringifyDocument(); + init_anchors(); + init_applyReviver(); + init_createNode(); + init_directives(); + Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } + }; + } +}); + +// node_modules/yaml/browser/dist/errors.js +var YAMLError, YAMLParseError, YAMLWarning, prettifyError; +var init_errors3 = __esm({ + "node_modules/yaml/browser/dist/errors.js"() { + YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } + }; + YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } + }; + YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } + }; + prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } + }; + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next: next2, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next2?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next2 && next2.type !== "space" && next2.type !== "newline" && next2.type !== "comma" && (next2.type !== "scalar" || next2.source !== "")) { + onError(next2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next2?.type === "block-map" || next2?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} +var init_resolve_props = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-props.js"() { + } +}); + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it2 of key.items) { + for (const st of it2.start) + if (st.type === "newline") + return true; + if (it2.sep) { + for (const st of it2.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it2.key) || containsNewline(it2.value)) + return true; + } + return false; + default: + return true; + } +} +var init_util_contains_newline = __esm({ + "node_modules/yaml/browser/dist/compose/util-contains-newline.js"() { + } +}); + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} +var init_util_flow_indent_check = __esm({ + "node_modules/yaml/browser/dist/compose/util-flow-indent-check.js"() { + init_util_contains_newline(); + } +}); + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} +var init_util_map_includes = __esm({ + "node_modules/yaml/browser/dist/compose/util-map-includes.js"() { + init_identity2(); + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} +var startColMsg; +var init_resolve_block_map = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-block-map.js"() { + init_Pair(); + init_YAMLMap(); + init_resolve_props(); + init_util_contains_newline(); + init_util_flow_indent_check(); + init_util_map_includes(); + startColMsg = "All mapping items must start at the same column"; + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} +var init_resolve_block_seq = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-block-seq.js"() { + init_YAMLSeq(); + init_resolve_props(); + init_util_flow_indent_check(); + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} +var init_resolve_end = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-end.js"() { + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} +var blockMsg, isBlock; +var init_resolve_flow_collection = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-flow-collection.js"() { + init_identity2(); + init_Pair(); + init_YAMLMap(); + init_YAMLSeq(); + init_resolve_end(); + init_resolve_props(); + init_util_contains_newline(); + init_util_map_includes(); + blockMsg = "Block collections are not allowed within flow collections"; + isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); + } +}); + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} +var init_compose_collection = __esm({ + "node_modules/yaml/browser/dist/compose/compose-collection.js"() { + init_identity2(); + init_Scalar(); + init_YAMLMap(); + init_YAMLSeq(); + init_resolve_block_map(); + init_resolve_block_seq(); + init_resolve_flow_collection(); + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} +var init_resolve_block_scalar = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-block-scalar.js"() { + init_Scalar(); + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} +var escapeCodes; +var init_resolve_flow_scalar = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js"() { + init_Scalar(); + init_resolve_end(); + escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " + }; + } +}); + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} +var init_compose_scalar = __esm({ + "node_modules/yaml/browser/dist/compose/compose-scalar.js"() { + init_identity2(); + init_Scalar(); + init_resolve_block_scalar(); + init_resolve_flow_scalar(); + } +}); + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} +var init_util_empty_scalar_position = __esm({ + "node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js"() { + } +}); + +// node_modules/yaml/browser/dist/compose/compose-node.js +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} +var CN; +var init_compose_node = __esm({ + "node_modules/yaml/browser/dist/compose/compose-node.js"() { + init_Alias(); + init_identity2(); + init_compose_collection(); + init_compose_scalar(); + init_resolve_end(); + init_util_empty_scalar_position(); + CN = { composeNode, composeEmptyNode }; + } +}); + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} +var init_compose_doc = __esm({ + "node_modules/yaml/browser/dist/compose/compose-doc.js"() { + init_Document(); + init_compose_node(); + init_resolve_end(); + init_resolve_props(); + } +}); + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer; +var init_composer = __esm({ + "node_modules/yaml/browser/dist/compose/composer.js"() { + init_directives(); + init_Document(); + init_errors3(); + init_identity2(); + init_compose_doc(); + init_resolve_end(); + Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it2 = dc.items[0]; + if (isPair(it2)) + it2 = it2.key; + const cb = it2.commentBefore; + it2.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } + }; + } +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} +var init_cst_scalar = __esm({ + "node_modules/yaml/browser/dist/parse/cst-scalar.js"() { + init_resolve_block_scalar(); + init_resolve_flow_scalar(); + init_errors3(); + init_stringifyString(); + } +}); + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} +var stringify2; +var init_cst_stringify = __esm({ + "node_modules/yaml/browser/dist/parse/cst-stringify.js"() { + stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); + } +}); + +// node_modules/yaml/browser/dist/parse/cst-visit.js +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} +var BREAK2, SKIP2, REMOVE2; +var init_cst_visit = __esm({ + "node_modules/yaml/browser/dist/parse/cst-visit.js"() { + BREAK2 = /* @__PURE__ */ Symbol("break visit"); + SKIP2 = /* @__PURE__ */ Symbol("skip children"); + REMOVE2 = /* @__PURE__ */ Symbol("remove item"); + visit2.BREAK = BREAK2; + visit2.SKIP = SKIP2; + visit2.REMOVE = REMOVE2; + visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; + }; + visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); + }; + } +}); + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} +var BOM, DOCUMENT, FLOW_END, SCALAR2, isCollection2, isScalar2; +var init_cst = __esm({ + "node_modules/yaml/browser/dist/parse/cst.js"() { + init_cst_scalar(); + init_cst_stringify(); + init_cst_visit(); + BOM = "\uFEFF"; + DOCUMENT = ""; + FLOW_END = ""; + SCALAR2 = ""; + isCollection2 = (token) => !!token && "items" in token; + isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); + } +}); + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits, tagChars, flowIndicatorChars, invalidAnchorChars, isNotAnchorChar, Lexer; +var init_lexer = __esm({ + "node_modules/yaml/browser/dist/parse/lexer.js"() { + init_cst(); + hexDigits = new Set("0123456789ABCDEFabcdef"); + tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); + flowIndicatorChars = new Set(",[]{}"); + invalidAnchorChars = new Set(" ,[]{}\n\r "); + isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); + Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next2 = this.next ?? "stream"; + while (next2 && (incomplete || this.hasChars(1))) + next2 = yield* this.parseNext(next2); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next2 = this.buffer[indent + offset + 1]; + if (next2 === "\n" || !next2 && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next2) { + switch (next2) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next2 = this.charAt(1); + if (this.flowKey || isEmpty(next2) || next2 === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next2 = this.buffer[i2 + 1]; + if (!next2 && !this.atEnd) + return this.setNext("block-scalar"); + if (next2 === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next2 = this.buffer[i + 1]; + if (isEmpty(next2) || inFlow && flowIndicatorChars.has(next2)) + break; + end = i; + } else if (isEmpty(ch)) { + let next2 = this.buffer[i + 1]; + if (ch === "\r") { + if (next2 === "\n") { + i += 1; + ch = "\n"; + next2 = this.buffer[i + 1]; + } else + end = i; + } + if (next2 === "#" || inFlow && flowIndicatorChars.has(next2)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } + }; + } +}); + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter; +var init_line_counter = __esm({ + "node_modules/yaml/browser/dist/parse/line-counter.js"() { + LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } + }; + } +}); + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it2 = parent.items[parent.items.length - 1]; + return it2.sep ?? it2.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it2 of fc.items) { + if (it2.sep && !it2.value && !includesToken(it2.start, "explicit-key-ind") && !includesToken(it2.sep, "map-value-ind")) { + if (it2.key) + it2.value = it2.key; + delete it2.key; + if (isFlowToken(it2.value)) { + if (it2.value.end) + arrayPushArray(it2.value.end, it2.sep); + else + it2.value.end = it2.sep; + } else + arrayPushArray(it2.start, it2.sep); + delete it2.sep; + } + } + } +} +var Parser; +var init_parser = __esm({ + "node_modules/yaml/browser/dist/parse/parser.js"() { + init_cst(); + init_lexer(); + Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it2 = top.items[top.items.length - 1]; + if (it2.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it2.sep) { + it2.value = token; + } else { + Object.assign(it2, { key: token, sep: [] }); + this.onKeyLine = !it2.explicitKey; + return; + } + break; + } + case "block-seq": { + const it2 = top.items[top.items.length - 1]; + if (it2.value) + top.items.push({ start: [], value: token }); + else + it2.value = token; + break; + } + case "flow-collection": { + const it2 = top.items[top.items.length - 1]; + if (!it2 || it2.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it2.sep) + it2.value = token; + else + Object.assign(it2, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it2 = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it2.value) { + const end = "end" in it2.value ? it2.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it2.sep) { + it2.sep.push(this.sourceToken); + } else { + it2.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it2.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it2.sep) { + it2.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it2.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it2.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it2.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it2.sep || it2.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it2.sep && !it2.value) { + const nl = []; + for (let i = 0; i < it2.sep.length; ++i) { + const st = it2.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it2.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it2.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it2.sep) { + it2.sep.push(this.sourceToken); + } else { + it2.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it2.sep && !it2.explicitKey) { + it2.start.push(this.sourceToken); + it2.explicitKey = true; + } else if (atNextItem || it2.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it2.explicitKey) { + if (!it2.sep) { + if (includesToken(it2.start, "newline")) { + Object.assign(it2, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it2.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it2.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it2.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it2.key) && !includesToken(it2.sep, "newline")) { + const start2 = getFirstKeyStartProps(it2.start); + const key = it2.key; + const sep = it2.sep; + sep.push(this.sourceToken); + delete it2.key; + delete it2.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it2.sep = it2.sep.concat(start, this.sourceToken); + } else { + it2.sep.push(this.sourceToken); + } + } else { + if (!it2.sep) { + Object.assign(it2, { key: null, sep: [this.sourceToken] }); + } else if (it2.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it2.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it2.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it2.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it2.sep) { + this.stack.push(fs2); + } else { + Object.assign(it2, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it2.explicitKey && it2.sep && !includesToken(it2.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it2 = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it2.value) { + const end = "end" in it2.value ? it2.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it2.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it2.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it2.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it2.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it2.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it2.value || this.indent <= seq2.indent) + break; + it2.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it2.value || includesToken(it2.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it2.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it2 = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it2 || it2.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it2.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it2 || it2.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it2.sep) + it2.sep.push(this.sourceToken); + else + Object.assign(it2, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it2 || it2.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it2.sep) + it2.sep.push(this.sourceToken); + else + it2.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it2 || it2.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it2.sep) + this.stack.push(fs2); + else + Object.assign(it2, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + }; + } +}); + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} +var init_public_api = __esm({ + "node_modules/yaml/browser/dist/public-api.js"() { + init_composer(); + init_Document(); + init_errors3(); + init_log(); + init_identity2(); + init_line_counter(); + init_parser(); + } +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); +var init_dist5 = __esm({ + "node_modules/yaml/browser/dist/index.js"() { + init_composer(); + init_Document(); + init_Schema(); + init_errors3(); + init_Alias(); + init_identity2(); + init_Pair(); + init_Scalar(); + init_YAMLMap(); + init_YAMLSeq(); + init_cst(); + init_lexer(); + init_line_counter(); + init_parser(); + init_public_api(); + init_visit(); + } +}); + +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); +var browser_default; +var init_browser = __esm({ + "node_modules/yaml/browser/index.js"() { + init_dist5(); + init_dist5(); + browser_default = dist_exports4; + } +}); + // node_modules/@earendil-works/pi-durable/dist/tools/env.js function requireEnv(api) { if (api.env === void 0) @@ -31061,7 +38267,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -31186,7 +38392,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -32317,8 +39523,8 @@ var init_string_enum = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -32398,7 +39604,7 @@ __export(dist_exports4, { withClientIdentity: () => withClientIdentity, withoutInitialSystemMessage: () => withoutInitialSystemMessage }); -var init_dist5 = __esm({ +var init_dist6 = __esm({ "node_modules/@earendil-works/pi-ai/dist/index.js"() { init_lazy(); init_context2(); @@ -32452,11 +39658,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -32693,7 +39899,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -32922,7 +40128,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -32940,8 +40151,9 @@ var ops2, encoder4, decoder4, ExtensionState, Metadata, fs; var init_extensions = __esm({ "extensions.ts"() { init_dist4(); + init_browser(); init_tools(); - init_dist5(); + init_dist6(); init_models(); init_dist3(); init_context(); @@ -33392,10 +40604,10 @@ var init_automations_pause_cases = __esm({ } ]); const { root: root2, harness: harness2 } = await f.open(); - const ultimate = await harness2.createConversation({ ownership: { kind: "ownerless" } }, BACKGROUND_CONTEXT); + const standing = await harness2.createConversation({ ownership: { kind: "ownerless" } }, BACKGROUND_CONTEXT); await harness2.commit(async (tx) => { ; - (await tx.doc(Standing, ROOT_CONVERSATION_ID)).ultimate = ultimate.id; + (await tx.doc(Standing, ROOT_CONVERSATION_ID))["$standing"] = standing.id; }, BACKGROUND_CONTEXT); const submission2 = await root2.submit({ type: "input", content: "go" }, BACKGROUND_CONTEXT); await until2(async () => (await f.action("state")).limit !== void 0); @@ -33409,7 +40621,7 @@ var init_automations_pause_cases = __esm({ const [generation] = await generations(harness2); expect(generation.record.state.status).not.toBe("terminal"); expect((await harness2.snapshot(LiveDoc, root2.id, BACKGROUND_CONTEXT))?.run).toBeDefined(); - const cards = async () => (await ultimate.context(BACKGROUND_CONTEXT)).entries.filter((entry2) => entry2.kind === "pause.limit"); + const cards = async () => (await standing.context(BACKGROUND_CONTEXT)).entries.filter((entry2) => entry2.kind === "pause.limit"); await until2(async () => (await cards()).length === 1); expect((await cards())[0].data).toMatchObject({ error: limit, conversationId: root2.id }); const played = await f.action("play"); @@ -33550,10 +40762,10 @@ var init_automations_pause_cases = __esm({ } ]); const { root: root2, harness: harness2 } = await f.open(); - const ultimate = await harness2.createConversation({ ownership: { kind: "ownerless" } }, BACKGROUND_CONTEXT); + const standing = await harness2.createConversation({ ownership: { kind: "ownerless" } }, BACKGROUND_CONTEXT); await harness2.commit(async (tx) => { ; - (await tx.doc(Standing, ROOT_CONVERSATION_ID)).ultimate = ultimate.id; + (await tx.doc(Standing, ROOT_CONVERSATION_ID))["$standing"] = standing.id; }, BACKGROUND_CONTEXT); const submission2 = await root2.submit({ type: "input", content: "go" }, BACKGROUND_CONTEXT); await until2(async () => (await f.action("state")).limit !== void 0); @@ -33561,8 +40773,8 @@ var init_automations_pause_cases = __esm({ expect((await f.action("state")).autoPlay).toBeUndefined(); expect(await f.autoPlay(since + 365 * 864e5)).toBe(false); expect(f.paused()).toBe(true); - const set = await f.setAutoPlay(30); - expect(set).toMatchObject({ autoPlay: 30, autoPlayAt: since + 30 * 6e4 }); + const set2 = await f.setAutoPlay(30); + expect(set2).toMatchObject({ autoPlay: 30, autoPlayAt: since + 30 * 6e4 }); expect(await f.autoPlay(since + 29 * 6e4)).toBe(false); expect(f.paused()).toBe(true); expect(await f.autoPlay(since + 30 * 6e4)).toBe(true); @@ -33570,14 +40782,14 @@ var init_automations_pause_cases = __esm({ expect((await submission2.wait(BACKGROUND_CONTEXT)).status).toBe("done"); expect(responses).toBe(2); expect(await f.autoPlay(since + 31 * 6e4)).toBe(false); - const played = (await ultimate.context(BACKGROUND_CONTEXT)).entries.filter( + const played = (await standing.context(BACKGROUND_CONTEXT)).entries.filter( (entry2) => entry2.kind === "pause.autoplay" ); expect(played).toHaveLength(1); expect(played[0].data).toMatchObject({ since, at: since + 30 * 6e4, minutes: 30 }); const notes = (await root2.context(BACKGROUND_CONTEXT)).entries.filter((entry2) => entry2.kind === "pause.note"); expect(notes[0].data).toMatchObject({ auto: true }); - expect(notes[0].model?.[0]?.content).toMatch(/continued after Ultimate played by itself\.$/); + expect(notes[0].model?.[0]?.content).toMatch(/continued after Standing agent played by itself\.$/); expect((await f.action("state")).autoPlay).toBe(30); }); it("never plays a pause the user pressed, also when a rate limit joins it", async () => { @@ -33616,7 +40828,7 @@ var init_automations_pause_cases = __esm({ it("treats message deliveries and routes as passive waiters", () => { expect(passive(at("board.delivery", "deliver"))).toBe(true); expect(passive(at("board.delivery", "reply"))).toBe(true); - expect(passive(at("ultimate.subagent-reporter", "deliver"))).toBe(true); + expect(passive(at("standing.subagent-reporter", "deliver"))).toBe(true); expect(passive(at("board.route", "observe"))).toBe(true); expect(passive(at("conversations.summary", "generate"))).toBe(false); }); diff --git a/host/js/automations-test-support.ts b/host/js/automations-test-support.ts index bd589f2..df24d62 100644 --- a/host/js/automations-test-support.ts +++ b/host/js/automations-test-support.ts @@ -1,4 +1,4 @@ -/** Minimal assertions for the imported Ultimate cases, without Node or Vitest. */ +/** Minimal assertions for the imported Standing agent cases, without Node or Vitest. */ export const cases: {name:string;run:()=>any}[]=[] export const it=(name:string,run:()=>any)=>cases.push({name,run}) export const describe=(_name:string,run:()=>any)=>run() diff --git a/host/js/bundle.js b/host/js/bundle.js index b6ca2fb..6b4db25 100644 --- a/host/js/bundle.js +++ b/host/js/bundle.js @@ -47,10 +47,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -112,8 +112,8 @@ var init_memory = __esm({ }); // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -247,13 +247,13 @@ var init_event_stream = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model3, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], - api: model3.api, - provider: model3.provider, - model: model3.id, + api: model2.api, + provider: model2.provider, + model: model2.id, usage: { input: 0, output: 0, @@ -264,7 +264,7 @@ function createSetupErrorMessage(model3, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -285,7 +285,7 @@ async function forwardStream(target, source, observer, observeResult) { target.end(result); observeResult(result); } -function lazyStream(model3, setup, observer) { +function lazyStream(model2, setup, observer) { const startedAt = Date.now(); const outer = new AssistantMessageEventStream(); let observedResult = false; @@ -296,7 +296,7 @@ function lazyStream(model3, setup, observer) { observer?.onResult?.(result); }; setup().then((inner) => forwardStream(outer, inner, observer, observeResult)).catch((error) => { - const message = createSetupErrorMessage(model3, error, startedAt); + const message = createSetupErrorMessage(model2, error, startedAt); const event = { type: "error", reason: "error", error: message }; outer.push(event); observer?.onEvent?.(event); @@ -307,23 +307,23 @@ function lazyStream(model3, setup, observer) { } function lazyApi(load, capabilities) { const api2 = { - stream: (model3, context, options) => lazyStream(model3, async () => (await load()).stream(model3, context, options)), - streamSimple: (model3, context, options) => lazyStream(model3, async () => (await load()).streamSimple(model3, context, options)) + stream: (model2, context, options) => lazyStream(model2, async () => (await load()).stream(model2, context, options)), + streamSimple: (model2, context, options) => lazyStream(model2, async () => (await load()).streamSimple(model2, context, options)) }; if (capabilities?.fetchDeferred) { - api2.fetchDeferred = (model3, handle, options) => lazyStream(model3, async () => { + api2.fetchDeferred = (model2, handle, options) => lazyStream(model2, async () => { const implementation = await load(); if (!implementation.fetchDeferred) throw new Error("API does not support deferred responses"); - return implementation.fetchDeferred(model3, handle, options); + return implementation.fetchDeferred(model2, handle, options); }); } if (capabilities?.cancelDeferred) { - api2.cancelDeferred = async (model3, handle, options) => { + api2.cancelDeferred = async (model2, handle, options) => { const implementation = await load(); if (!implementation.cancelDeferred) throw new Error("API cannot cancel deferred responses"); - await implementation.cancelDeferred(model3, handle, options); + await implementation.cancelDeferred(model2, handle, options); }; } return api2; @@ -1003,15 +1003,15 @@ function withClientIdentity(models2, identity) { getAuth: models2.getAuth.bind(models2), login: (providerId, type, interaction, options) => models2.login(providerId, type, interaction, options), logout: (providerId, options) => models2.logout(providerId, options), - stream: (model3, context, options) => models2.stream(model3, context, withIdentity(options)), - complete: (model3, context, options) => models2.complete(model3, context, withIdentity(options)), - streamSimple: (model3, context, options) => models2.streamSimple(model3, context, withIdentity(options)), - completeSimple: (model3, context, options) => models2.completeSimple(model3, context, withIdentity(options)), - streamDeferred: (model3, handle, options) => models2.streamDeferred(model3, handle, withIdentity(options)), - fetchDeferred: (model3, handle, options) => models2.fetchDeferred(model3, handle, withIdentity(options)), - cancelDeferred: (model3, handle, options) => models2.cancelDeferred(model3, handle, withIdentity(options)), - generateImages: (model3, context, options) => models2.generateImages(model3, context, withIdentity(options)), - classify: (model3, context, options) => models2.classify(model3, context, withIdentity(options)) + stream: (model2, context, options) => models2.stream(model2, context, withIdentity(options)), + complete: (model2, context, options) => models2.complete(model2, context, withIdentity(options)), + streamSimple: (model2, context, options) => models2.streamSimple(model2, context, withIdentity(options)), + completeSimple: (model2, context, options) => models2.completeSimple(model2, context, withIdentity(options)), + streamDeferred: (model2, handle, options) => models2.streamDeferred(model2, handle, withIdentity(options)), + fetchDeferred: (model2, handle, options) => models2.fetchDeferred(model2, handle, withIdentity(options)), + cancelDeferred: (model2, handle, options) => models2.cancelDeferred(model2, handle, withIdentity(options)), + generateImages: (model2, context, options) => models2.generateImages(model2, context, withIdentity(options)), + classify: (model2, context, options) => models2.classify(model2, context, withIdentity(options)) }; if (!isMutableModels(models2)) return wrapped; @@ -1034,48 +1034,48 @@ var init_identity = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/utils/model-operations.js -function getModelType(model3) { - return model3.type ?? "chat"; +function getModelType(model2) { + return model2.type ?? "chat"; } -function isModelType(model3, type) { - return getModelType(model3) === type; +function isModelType(model2, type) { + return getModelType(model2) === type; } -function assertChatModel(model3) { - if (!isModelType(model3, "chat")) { - throw new ModelsError("provider", `Model ${model3.provider}/${model3.id} is not a chat model`); +function assertChatModel(model2) { + if (!isModelType(model2, "chat")) { + throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} is not a chat model`); } } -function assertImageModel(model3) { - if (!isModelType(model3, "image")) { - throw new ModelsError("provider", `Model ${model3.provider}/${model3.id} is not an image model`); +function assertImageModel(model2) { + if (!isModelType(model2, "image")) { + throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} is not an image model`); } } -function assertClassifierModel(model3) { - if (!isModelType(model3, "classifier")) { - throw new ModelsError("provider", `Model ${model3.provider}/${model3.id} is not a classifier model`); +function assertClassifierModel(model2) { + if (!isModelType(model2, "classifier")) { + throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} is not a classifier model`); } } -function assertClassifierInputSupported(model3, context) { - if (context.images?.length && !model3.input.includes("image")) { - throw new ModelsError("provider", `Model ${model3.provider}/${model3.id} does not accept image input`); +function assertClassifierInputSupported(model2, context) { + if (context.images?.length && !model2.input.includes("image")) { + throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} does not accept image input`); } } -function imageErrorResult(model3, error, aborted = false) { +function imageErrorResult(model2, error, aborted = false) { return { - api: model3.api, - provider: model3.provider, - model: model3.id, + api: model2.api, + provider: model2.provider, + model: model2.id, output: [], stopReason: aborted ? "aborted" : "error", errorMessage: error instanceof Error ? error.message : String(error), timestamp: Date.now() }; } -function classifierErrorResult(model3, error, aborted = false) { +function classifierErrorResult(model2, error, aborted = false) { return { - api: model3.api, - provider: model3.provider, - model: model3.id, + api: model2.api, + provider: model2.provider, + model: model2.id, answers: {}, stopReason: aborted ? "aborted" : "error", errorMessage: error instanceof Error ? error.message : String(error), @@ -1131,11 +1131,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text2 = contentText(message.content); if (text2.length > 0) content.push(text2); @@ -1147,14 +1147,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -1267,8 +1267,8 @@ __export(models_exports, { isModelType: () => isModelType, modelsAreEqual: () => modelsAreEqual }); -function hasKnownModelType(model3) { - return Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model3)); +function hasKnownModelType(model2) { + return Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model2)); } function withKnownModelTypes(entry2) { return { ...entry2, models: entry2.models.filter(hasKnownModelType) }; @@ -1306,21 +1306,21 @@ function createProvider(input) { const fetchModels = input.fetchModels; const currentModels2 = () => { const merged = [...baselineModels]; - for (const model3 of dynamicModels) { - const index = merged.findIndex((entry2) => getModelType(entry2) === getModelType(model3) && entry2.id === model3.id); + for (const model2 of dynamicModels) { + const index = merged.findIndex((entry2) => getModelType(entry2) === getModelType(model2) && entry2.id === model2.id); if (index >= 0) - merged[index] = model3; + merged[index] = model2; else - merged.push(model3); + merged.push(model2); } return merged; }; - const apiFor = (model3) => single ?? byApi?.[model3.api]; - const dispatch = (model3, run2) => { - const streams2 = apiFor(model3); + const apiFor = (model2) => single ?? byApi?.[model2.api]; + const dispatch = (model2, run2) => { + const streams2 = apiFor(model2); if (!streams2) { - return lazyStream(model3, async () => { - throw new ModelsError("stream", `Provider ${input.id} has no API implementation for "${model3.api}"`); + return lazyStream(model2, async () => { + throw new ModelsError("stream", `Provider ${input.id} has no API implementation for "${model2.api}"`); }); } return run2(streams2); @@ -1331,11 +1331,11 @@ function createProvider(input) { baseUrl: input.baseUrl, headers: input.headers, auth: input.auth, - getModels: () => currentModels2().filter((model3) => isModelType(model3, "chat")), + getModels: () => currentModels2().filter((model2) => isModelType(model2, "chat")), getAllModels: currentModels2, refreshModels: fetchModels ? async (context) => { if (context.stored) { - const restored = context.stored.models.filter((model3) => model3.provider === input.id).map((model3) => model3); + const restored = context.stored.models.filter((model2) => model2.provider === input.id).map((model2) => model2); if (!await context.publish({ update: () => { dynamicModels = restored; @@ -1359,55 +1359,55 @@ function createProvider(input) { } : void 0, filterModels: input.filterModels, filterAllModels: input.filterAllModels, - stream: (model3, context, options) => dispatch(model3, (streams2) => streams2.stream(model3, context, options)), - streamSimple: (model3, context, options) => dispatch(model3, (streams2) => streams2.streamSimple(model3, context, options)) + stream: (model2, context, options) => dispatch(model2, (streams2) => streams2.stream(model2, context, options)), + streamSimple: (model2, context, options) => dispatch(model2, (streams2) => streams2.streamSimple(model2, context, options)) }; if (streams.some((entry2) => entry2.fetchDeferred !== void 0)) { - provider2.fetchDeferred = (model3, handle, options) => lazyStream(model3, async () => { - const implementation = apiFor(model3); + provider2.fetchDeferred = (model2, handle, options) => lazyStream(model2, async () => { + const implementation = apiFor(model2); if (!implementation?.fetchDeferred) { - throw new ModelsError("provider", `Provider ${input.id} does not support deferred responses for "${model3.api}"`); + throw new ModelsError("provider", `Provider ${input.id} does not support deferred responses for "${model2.api}"`); } - return implementation.fetchDeferred(model3, handle, options); + return implementation.fetchDeferred(model2, handle, options); }); } if (streams.some((entry2) => entry2.cancelDeferred !== void 0)) { - provider2.cancelDeferred = async (model3, handle, options) => { - const implementation = apiFor(model3); + provider2.cancelDeferred = async (model2, handle, options) => { + const implementation = apiFor(model2); if (!implementation?.cancelDeferred) { - throw new ModelsError("provider", `Provider ${input.id} cannot cancel deferred responses for "${model3.api}"`); + throw new ModelsError("provider", `Provider ${input.id} cannot cancel deferred responses for "${model2.api}"`); } - await implementation.cancelDeferred(model3, handle, options); + await implementation.cancelDeferred(model2, handle, options); }; } if (images && imageImplementations.length > 0) { - provider2.generateImages = async (model3, context, options) => { - const implementation = images[model3.api]; + provider2.generateImages = async (model2, context, options) => { + const implementation = images[model2.api]; if (!implementation) { - return imageErrorResult(model3, new ModelsError("provider", `Provider ${input.id} has no image generation implementation for "${model3.api}"`)); + return imageErrorResult(model2, new ModelsError("provider", `Provider ${input.id} has no image generation implementation for "${model2.api}"`)); } - return implementation.generateImages(model3, context, options); + return implementation.generateImages(model2, context, options); }; } if (classifiers && classifierImplementations.length > 0) { - provider2.classify = async (model3, context, options) => { - const implementation = classifiers[model3.api]; + provider2.classify = async (model2, context, options) => { + const implementation = classifiers[model2.api]; if (!implementation) { - return classifierErrorResult(model3, new ModelsError("provider", `Provider ${input.id} has no classifier implementation for "${model3.api}"`)); + return classifierErrorResult(model2, new ModelsError("provider", `Provider ${input.id} has no classifier implementation for "${model2.api}"`)); } - return implementation.classify(model3, context, options); + return implementation.classify(model2, context, options); }; } return provider2; } -function hasApi(model3, api2) { - return isModelType(model3, "chat") && model3.api === api2; +function hasApi(model2, api2) { + return isModelType(model2, "chat") && model2.api === api2; } -function calculateCost(model3, usage) { +function calculateCost(model2, usage) { const inputTokens = usage.input + usage.cacheRead + usage.cacheWrite; - let rates = model3.cost; + let rates = model2.cost; let matchedThreshold = -1; - for (const tier of model3.cost.tiers ?? []) { + for (const tier of model2.cost.tiers ?? []) { if (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) { rates = tier; matchedThreshold = tier.inputTokensAbove; @@ -1423,11 +1423,11 @@ function calculateCost(model3, usage) { usage.cost.totalFromProvider = false; return usage.cost; } -function getSupportedThinkingLevels(model3) { - if (!model3.reasoning) +function getSupportedThinkingLevels(model2) { + if (!model2.reasoning) return ["off"]; return EXTENDED_THINKING_LEVELS.filter((level) => { - const mapped = model3.thinkingLevelMap?.[level]; + const mapped = model2.thinkingLevelMap?.[level]; if (mapped === null) return false; if (level === "xhigh" || level === "max") @@ -1435,8 +1435,8 @@ function getSupportedThinkingLevels(model3) { return true; }); } -function clampThinkingLevel(model3, level) { - const availableLevels = getSupportedThinkingLevels(model3); +function clampThinkingLevel(model2, level) { + const availableLevels = getSupportedThinkingLevels(model2); if (availableLevels.includes(level)) return level; const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level); @@ -1552,13 +1552,13 @@ var init_models = __esm({ return models2; } getModelsOfType(type, provider2) { - return this.getAllModels(provider2).filter((model3) => isModelType(model3, type)); + return this.getAllModels(provider2).filter((model2) => isModelType(model2, type)); } getModel(provider2, id) { - return this.getModels(provider2).find((model3) => model3.id === id); + return this.getModels(provider2).find((model2) => model2.id === id); } getModelOfType(type, provider2, id) { - return this.getModelsOfType(type, provider2).find((model3) => model3.id === id); + return this.getModelsOfType(type, provider2).find((model2) => model2.id === id); } supersedeProviderRefresh(providerId) { const generation = (this.refreshGenerations.get(providerId) ?? 0) + 1; @@ -1743,7 +1743,7 @@ var init_models = __esm({ return raceWithAbortSignal(available, signal); } async getAvailableOfType(type, providerId, options) { - return (await this.getAllAvailable(providerId, options)).filter((model3) => isModelType(model3, type)); + return (await this.getAllAvailable(providerId, options)).filter((model2) => isModelType(model2, type)); } getAllAvailable(providerId, options) { const signal = operationSignal(options?.signal); @@ -1755,8 +1755,8 @@ var init_models = __esm({ return provider2.filterAllModels(models2, credential); if (!provider2.filterModels) return models2; - const availableChatIds = new Set(provider2.filterModels(provider2.getModels(), credential).map((model3) => model3.id)); - return models2.filter((model3) => !isModelType(model3, "chat") || availableChatIds.has(model3.id)); + const availableChatIds = new Set(provider2.filterModels(provider2.getModels(), credential).map((model2) => model2.id)); + return models2.filter((model2) => !isModelType(model2, "chat") || availableChatIds.has(model2.id)); }); })(); return raceWithAbortSignal(available, signal); @@ -1836,30 +1836,30 @@ var init_models = __esm({ throw new ModelsError("auth", `Credential store delete failed for ${providerId}`, { cause: error }); } } - requireProvider(model3) { - const provider2 = this.providers.get(model3.provider); + requireProvider(model2) { + const provider2 = this.providers.get(model2.provider); if (!provider2) { - throw new ModelsError("provider", `Unknown provider: ${model3.provider}`); + throw new ModelsError("provider", `Unknown provider: ${model2.provider}`); } return provider2; } - requireChatProvider(model3) { - assertChatModel(model3); - return this.requireProvider(model3); + requireChatProvider(model2) { + assertChatModel(model2); + return this.requireProvider(model2); } - async applyAuth(model3, options) { - this.requireProvider(model3); - const resolution = await this.getAuth(model3, { + async applyAuth(model2, options) { + this.requireProvider(model2); + const resolution = await this.getAuth(model2, { apiKey: options?.apiKey, env: options?.env, signal: options?.signal }); if (!resolution) { - throw new ModelsError("auth", `Provider is not configured: ${model3.provider}`); + throw new ModelsError("auth", `Provider is not configured: ${model2.provider}`); } const auth = resolution.auth; const apiKey = options?.apiKey ?? auth.apiKey; - const requestModel = auth.baseUrl ? { ...model3, baseUrl: auth.baseUrl } : model3; + const requestModel = auth.baseUrl ? { ...model2, baseUrl: auth.baseUrl } : model2; const sessionId = options && "sessionId" in options && typeof options.sessionId === "string" ? options.sessionId : void 0; let headers = mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel, sessionId), auth.headers), options?.headers); if (options?.transformHeaders) @@ -1876,74 +1876,74 @@ var init_models = __esm({ }; return { requestModel, requestOptions }; } - stream(model3, context, options) { + stream(model2, context, options) { const transcript = normalizeContext(context); - return lazyStream(model3, async () => { - const provider2 = this.requireChatProvider(model3); - const { requestModel, requestOptions } = await this.applyAuth(model3, options); + return lazyStream(model2, async () => { + const provider2 = this.requireChatProvider(model2); + const { requestModel, requestOptions } = await this.applyAuth(model2, options); return provider2.stream(requestModel, transcript, requestOptions); - }, observeModelRequest(model3, options, false)); + }, observeModelRequest(model2, options, false)); } - async complete(model3, context, options) { - return this.stream(model3, context, options).result(); + async complete(model2, context, options) { + return this.stream(model2, context, options).result(); } - streamSimple(model3, context, options) { + streamSimple(model2, context, options) { const transcript = normalizeContext(context); - return lazyStream(model3, async () => { - const provider2 = this.requireChatProvider(model3); - const { requestModel, requestOptions } = await this.applyAuth(model3, options); + return lazyStream(model2, async () => { + const provider2 = this.requireChatProvider(model2); + const { requestModel, requestOptions } = await this.applyAuth(model2, options); return provider2.streamSimple(requestModel, transcript, requestOptions); - }, observeModelRequest(model3, options, false)); + }, observeModelRequest(model2, options, false)); } - async completeSimple(model3, context, options) { - return this.streamSimple(model3, context, options).result(); + async completeSimple(model2, context, options) { + return this.streamSimple(model2, context, options).result(); } - streamDeferred(model3, handle, options) { - return lazyStream(model3, async () => { - const provider2 = this.requireChatProvider(model3); + streamDeferred(model2, handle, options) { + return lazyStream(model2, async () => { + const provider2 = this.requireChatProvider(model2); if (!provider2.fetchDeferred) { - throw new ModelsError("provider", `Provider ${model3.provider} does not support deferred responses`); + throw new ModelsError("provider", `Provider ${model2.provider} does not support deferred responses`); } - const { requestModel, requestOptions } = await this.applyAuth(model3, options); + const { requestModel, requestOptions } = await this.applyAuth(model2, options); return provider2.fetchDeferred(requestModel, handle, requestOptions); - }, observeModelRequest(model3, options, true)); + }, observeModelRequest(model2, options, true)); } - async fetchDeferred(model3, handle, options) { - return this.streamDeferred(model3, handle, options).result(); + async fetchDeferred(model2, handle, options) { + return this.streamDeferred(model2, handle, options).result(); } - async cancelDeferred(model3, handle, options) { - const provider2 = this.requireChatProvider(model3); + async cancelDeferred(model2, handle, options) { + const provider2 = this.requireChatProvider(model2); if (!provider2.cancelDeferred) { - throw new ModelsError("provider", `Provider ${model3.provider} does not support deferred responses`); + throw new ModelsError("provider", `Provider ${model2.provider} does not support deferred responses`); } - const { requestModel, requestOptions } = await this.applyAuth(model3, options); + const { requestModel, requestOptions } = await this.applyAuth(model2, options); await provider2.cancelDeferred(requestModel, handle, requestOptions); } - async generateImages(model3, context, options) { + async generateImages(model2, context, options) { try { - assertImageModel(model3); - const provider2 = this.requireProvider(model3); + assertImageModel(model2); + const provider2 = this.requireProvider(model2); if (!provider2.generateImages) { - throw new ModelsError("provider", `Provider ${model3.provider} does not support image generation`); + throw new ModelsError("provider", `Provider ${model2.provider} does not support image generation`); } - const { requestModel, requestOptions } = await this.applyAuth(model3, options); + const { requestModel, requestOptions } = await this.applyAuth(model2, options); return await provider2.generateImages(requestModel, context, requestOptions); } catch (error) { - return imageErrorResult(model3, error, options?.signal?.aborted); + return imageErrorResult(model2, error, options?.signal?.aborted); } } - async classify(model3, context, options) { + async classify(model2, context, options) { try { - assertClassifierModel(model3); - assertClassifierInputSupported(model3, context); - const provider2 = this.requireProvider(model3); + assertClassifierModel(model2); + assertClassifierInputSupported(model2, context); + const provider2 = this.requireProvider(model2); if (!provider2.classify) { - throw new ModelsError("provider", `Provider ${model3.provider} does not support classification`); + throw new ModelsError("provider", `Provider ${model2.provider} does not support classification`); } - const { requestModel, requestOptions } = await this.applyAuth(model3, options); + const { requestModel, requestOptions } = await this.applyAuth(model2, options); return await provider2.classify(requestModel, context, requestOptions); } catch (error) { - return classifierErrorResult(model3, error, options?.signal?.aborted); + return classifierErrorResult(model2, error, options?.signal?.aborted); } } }; @@ -2177,15 +2177,15 @@ function requiredNumber(label, value2, field) { } return value2; } -function requestHeaders(model3, apiKey, optionsHeaders, identity) { - return providerHeadersToRecord(getIdentityHeaders(model3, identity), { authorization: `Bearer ${apiKey}`, "content-type": "application/json" }, model3.headers, optionsHeaders) ?? {}; +function requestHeaders(model2, apiKey, optionsHeaders, identity) { + return providerHeadersToRecord(getIdentityHeaders(model2, identity), { authorization: `Bearer ${apiKey}`, "content-type": "application/json" }, model2.headers, optionsHeaders) ?? {}; } -async function postClassifierRequest(label, url, model3, body, options, noRetryStatuses) { +async function postClassifierRequest(label, url, model2, body, options, noRetryStatuses) { if (!options?.apiKey) - throw new Error(`No API key for provider: ${model3.provider}`); + throw new Error(`No API key for provider: ${model2.provider}`); const apiKey = options.apiKey; let payload = body; - const transformed = await options.onPayload?.(payload, model3); + const transformed = await options.onPayload?.(payload, model2); if (transformed !== void 0) payload = transformed; const requestFetch = options.fetch ?? globalThis.fetch; @@ -2195,7 +2195,7 @@ async function postClassifierRequest(label, url, model3, body, options, noRetryS try { const next = await requestFetch(url, { method: "POST", - headers: requestHeaders(model3, apiKey, options.headers, options.identity), + headers: requestHeaders(model2, apiKey, options.headers, options.identity), body: JSON.stringify(payload), signal }); @@ -2213,13 +2213,13 @@ async function postClassifierRequest(label, url, model3, body, options, noRetryS signal: options.signal, noRetryStatuses }); - await options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model3); + await options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model2); return json; } function tokenCount(value2) { return typeof value2 === "number" && Number.isFinite(value2) && value2 > 0 ? value2 : 0; } -function parseClassifierUsage(value2, model3) { +function parseClassifierUsage(value2, model2) { if (!isRecord(value2) || value2.input_tokens === void 0 && value2.output_tokens === void 0) return void 0; const input = tokenCount(value2.input_tokens); @@ -2232,7 +2232,7 @@ function parseClassifierUsage(value2, model3) { totalTokens: input + output, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }; - calculateCost(model3, usage); + calculateCost(model2, usage); return usage; } var init_classifier_shared = __esm({ @@ -2364,26 +2364,26 @@ var init_openai_decisions = __esm({ LABEL = "OpenAI Decisions"; MAX_IMAGES = 128; NO_RETRY_STATUSES = [504]; - classify = async (model3, context, options) => { + classify = async (model2, context, options) => { const output = { - api: model3.api, - provider: model3.provider, - model: model3.id, + api: model2.api, + provider: model2.provider, + model: model2.id, answers: {}, stopReason: "stop", timestamp: Date.now() }; try { - if (model3.api !== "openai-decisions") - throw new Error(`Unsupported classifier API: ${model3.api}`); - const body = await postClassifierRequest(LABEL, new URL("decisions", `${model3.baseUrl.replace(/\/+$/u, "")}/`), model3, { - model: model3.id, + if (model2.api !== "openai-decisions") + throw new Error(`Unsupported classifier API: ${model2.api}`); + const body = await postClassifierRequest(LABEL, new URL("decisions", `${model2.baseUrl.replace(/\/+$/u, "")}/`), model2, { + model: model2.id, input: wireInput(context), questions: Object.entries(context.questions).map(([id, question]) => wireQuestion(id, question)) }, options, NO_RETRY_STATUSES); if (!isRecord(body)) throw new Error(`${LABEL} returned an unexpected response`); - const usage = parseClassifierUsage(body.usage, model3); + const usage = parseClassifierUsage(body.usage, model2); if (usage) output.usage = usage; output.answers = parseAnswers(body.answers, context); @@ -4109,22 +4109,22 @@ var init_utils = __esm({ if (str2.length === 0) { return str2; } - let string = str2; + let string2 = str2; if (typeof str2 === "symbol") { - string = Symbol.prototype.toString.call(str2); + string2 = Symbol.prototype.toString.call(str2); } else if (typeof str2 !== "string") { - string = String(str2); + string2 = String(str2); } if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, ($0) => "%26%23" + Number.parseInt($0.slice(2), 16) + "%3B"); + return escape(string2).replace(/%u[0-9a-f]{4}/gi, ($0) => "%26%23" + Number.parseInt($0.slice(2), 16) + "%3B"); } let out = ""; - for (let j = 0; j < string.length; ) { - let segmentEnd = Math.min((Math.floor(j / limit) + 1) * limit, string.length); - if (segmentEnd < string.length && string.codePointAt(segmentEnd - 1) > 65535) { + for (let j = 0; j < string2.length; ) { + let segmentEnd = Math.min((Math.floor(j / limit) + 1) * limit, string2.length); + if (segmentEnd < string2.length && string2.codePointAt(segmentEnd - 1) > 65535) { segmentEnd += 1; } - const segment = string.length >= limit ? string.slice(j, segmentEnd) : string; + const segment = string2.length >= limit ? string2.slice(j, segmentEnd) : string2; const arr2 = []; for (let i = 0; i < segment.length; ++i) { let c = segment.charCodeAt(i); @@ -6906,7 +6906,7 @@ function getRetainedStorageBrand(current) { } return void 0; } -function estimateRetainedBufferBytes(current, visit, depth) { +function estimateRetainedBufferBytes(current, visit3, depth) { if (ArrayBuffer.isView(current)) { let buffer; let kind2 = "typed-array"; @@ -6919,7 +6919,7 @@ function estimateRetainedBufferBytes(current, visit, depth) { if (typeof buffer !== "object" || buffer === null) { return { bytes: Number.POSITIVE_INFINITY, kind: kind2 }; } - visit(buffer, depth + 1); + visit3(buffer, depth + 1); return { bytes: 0, kind: kind2 }; } const brand = getRetainedStorageBrand(current); @@ -6964,17 +6964,17 @@ function estimateRetainedBufferBytes(current, visit, depth) { kind }; } -function visitHiddenEventValues(current, kind, visit) { +function visitHiddenEventValues(current, kind, visit3) { if (kind === "map") { for (const [key, entry2] of mapEntries.call(current)) { - if (!visit(key, 8) || !visit(entry2, 8)) { + if (!visit3(key, 8) || !visit3(entry2, 8)) { return false; } } } if (kind === "set") { for (const entry2 of setValues.call(current)) { - if (!visit(entry2, 8)) { + if (!visit3(entry2, 8)) { return false; } } @@ -6984,7 +6984,7 @@ function visitHiddenEventValues(current, kind, visit) { return false; } for (const [name, value2] of headersEntries.call(current)) { - if (!visit(name, 8) || !visit(value2, 8)) { + if (!visit3(name, 8) || !visit3(value2, 8)) { return false; } } @@ -7014,7 +7014,7 @@ function getInspectableEventKeys(current, kind, availableBytes) { return !Number.isInteger(index) || index < 0 || index >= length || String(index) !== key; }); } -function visitInspectableEventProperties(current, kind, depth, availableBytes, charge, visit) { +function visitInspectableEventProperties(current, kind, depth, availableBytes, charge, visit3) { const keys = getInspectableEventKeys(current, kind, availableBytes()); if (keys === void 0) { return false; @@ -7024,7 +7024,7 @@ function visitInspectableEventProperties(current, kind, depth, availableBytes, c return false; } if (typeof key === "symbol") { - visit(key, depth + 1); + visit3(key, depth + 1); } const descriptor = Object.getOwnPropertyDescriptor(current, key); if (!descriptor) { @@ -7036,11 +7036,11 @@ function visitInspectableEventProperties(current, kind, depth, availableBytes, c } return false; } - visit(descriptor.value, depth + 1, kind === "blob"); + visit3(descriptor.value, depth + 1, kind === "blob"); } return true; } -function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit, retainPrototype) { +function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit3, retainPrototype) { let prototype = Object.getPrototypeOf(current); for (let prototypeDepth = depth + 1; prototype !== null; prototypeDepth += 1) { if (prototypeDepth >= MAX_BUFFERED_EVENT_DEPTH) { @@ -7050,7 +7050,7 @@ function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visi return true; } if (visited.has(prototype)) { - visit(prototype, prototypeDepth); + visit3(prototype, prototypeDepth); return availableBytes() >= 0; } visited.add(prototype); @@ -7061,7 +7061,7 @@ function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visi } const intrinsic = getTrustedForeignIntrinsic(retainedPrototype); if (!intrinsic) { - return visitInspectableEventProperties(retainedPrototype, void 0, prototypeDepth, availableBytes, charge, visit); + return visitInspectableEventProperties(retainedPrototype, void 0, prototypeDepth, availableBytes, charge, visit3); } for (const key of Reflect.ownKeys(retainedPrototype)) { const descriptor = Object.getOwnPropertyDescriptor(retainedPrototype, key); @@ -7075,9 +7075,9 @@ function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visi return false; } if (typeof key === "symbol") { - visit(key, prototypeDepth + 1); + visit3(key, prototypeDepth + 1); } - visit(descriptor.value, prototypeDepth + 1); + visit3(descriptor.value, prototypeDepth + 1); } return availableBytes() >= 0; }); @@ -7146,7 +7146,7 @@ function inspectBufferedEventGraph(value2, remainingBytes) { bytes2 = remainingBytes + 1; } }; - const visit = (current, depth, isBlobInternalHandle = false) => { + const visit3 = (current, depth, isBlobInternalHandle = false) => { if (bytes2 > remainingBytes) { return; } @@ -7184,8 +7184,8 @@ function inspectBufferedEventGraph(value2, remainingBytes) { if (!charge(16)) { return false; } - const retainedStorage = estimateRetainedBufferBytes(current, visit, depth); - if (!visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit, retainIdentity)) { + const retainedStorage = estimateRetainedBufferBytes(current, visit3, depth); + if (!visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit3, retainIdentity)) { return false; } if (retainedStorage !== void 0 && !charge(retainedStorage.bytes)) { @@ -7195,18 +7195,18 @@ function inspectBufferedEventGraph(value2, remainingBytes) { if (!charge(overhead)) { return false; } - visit(hiddenValue, depth + 1); + visit3(hiddenValue, depth + 1); return bytes2 <= remainingBytes; })) { return false; } - return visitInspectableEventProperties(current, retainedStorage?.kind, depth, availableBytes, charge, visit); + return visitInspectableEventProperties(current, retainedStorage?.kind, depth, availableBytes, charge, visit3); })) { bytes2 = remainingBytes + 1; } }; try { - visit(value2, 0); + visit3(value2, 0); } catch { return void 0; } @@ -9053,7 +9053,7 @@ function captureSnapshotArrayItem(array, index) { } return descriptor.value; } -function mapCapturedSnapshotArray(array, maximum, kind, map2) { +function mapCapturedSnapshotArray(array, maximum, kind, map3) { const descriptor = Object.getOwnPropertyDescriptor(array, "length"); const length = descriptor && "value" in descriptor ? descriptor.value : void 0; if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > maximum) { @@ -9069,7 +9069,7 @@ function mapCapturedSnapshotArray(array, maximum, kind, map2) { if (!("value" in item)) { throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot"); } - mapped[index] = map2(item.value, index); + mapped[index] = map3(item.value, index); } return mapped; } @@ -9182,7 +9182,7 @@ function canonicalSerializedParserSchema(value2, budget) { budget.bytes += bytes2; return true; }; - const visit = (current, depth) => { + const visit3 = (current, depth) => { if (depth > MAX_SERIALIZED_PARSER_SCHEMA_DEPTH || budget.nodes >= MAX_SERIALIZED_PARSER_SCHEMA_NODES) { return UNSAFE_SERIALIZED_PARSER_VALUE; } @@ -9250,7 +9250,7 @@ function canonicalSerializedParserSchema(value2, budget) { if (!("value" in descriptor)) { return UNSAFE_SERIALIZED_PARSER_VALUE; } - const item = visit(descriptor.value, depth + 1); + const item = visit3(descriptor.value, depth + 1); if (item === UNSAFE_SERIALIZED_PARSER_VALUE) { return item; } @@ -9287,7 +9287,7 @@ function canonicalSerializedParserSchema(value2, budget) { }); const fields = []; for (const [key, entry2] of entries2) { - const normalized = visit(entry2, depth + 1); + const normalized = visit3(entry2, depth + 1); if (normalized === UNSAFE_SERIALIZED_PARSER_VALUE) { return normalized; } @@ -9305,7 +9305,7 @@ function canonicalSerializedParserSchema(value2, budget) { } }; try { - const normalized = visit(value2, 0); + const normalized = visit3(value2, 0); return typeof normalized === "string" ? normalized : void 0; } catch { return void 0; @@ -9313,11 +9313,11 @@ function canonicalSerializedParserSchema(value2, budget) { } function rememberSerializedParserSchema(signatures, source, holder, key) { const parser = Object.getOwnPropertyDescriptor(source, "$parseRaw"); - const schema = Object.getOwnPropertyDescriptor(holder, key); - if (!parser || !("value" in parser) || typeof parser.value !== "function" || !schema || !("value" in schema)) { + const schema4 = Object.getOwnPropertyDescriptor(holder, key); + if (!parser || !("value" in parser) || typeof parser.value !== "function" || !schema4 || !("value" in schema4)) { return; } - const normalized = canonicalSerializedParserSchema(schema.value, { nodes: 0, bytes: 0 }); + const normalized = canonicalSerializedParserSchema(schema4.value, { nodes: 0, bytes: 0 }); if (normalized !== void 0) { signatures.set(source, normalized); } @@ -9405,7 +9405,7 @@ function observeSerializedChatCompletionParserParams(body, initial, update) { if (initial.response_format) { rememberSerializedParserSchema(originalSchemaSignatures, initial.response_format, initial.response_format, "json_schema"); } - let root2; + let root; let tools; let responseFormat; let responseFrame; @@ -9415,8 +9415,8 @@ function observeSerializedChatCompletionParserParams(body, initial, update) { let functionFrames = /* @__PURE__ */ new WeakMap(); return observeJSONRequestBody(body, { value(holder, key, value2) { - if (!root2 && key === "" && typeof value2 === "object" && value2 !== null) { - root2 = value2; + if (!root && key === "" && typeof value2 === "object" && value2 !== null) { + root = value2; tools = void 0; responseFormat = void 0; responseFrame = void 0; @@ -9426,7 +9426,7 @@ function observeSerializedChatCompletionParserParams(body, initial, update) { functionFrames = /* @__PURE__ */ new WeakMap(); return; } - if (holder === root2 && key === "response_format") { + if (holder === root && key === "response_format") { if (typeof value2 === "object" && value2 !== null) { responseFormat = value2; const owner = ownSerializedParserObject(holder, key); @@ -9437,7 +9437,7 @@ function observeSerializedChatCompletionParserParams(body, initial, update) { } return; } - if (holder === root2 && key === "tools") { + if (holder === root && key === "tools") { if (Array.isArray(value2)) { tools = new Proxy(value2, { get(target, property) { @@ -9499,7 +9499,7 @@ function observeSerializedChatCompletionParserParams(body, initial, update) { return void 0; }, complete() { - if (!root2) { + if (!root) { return; } const snapshot = cloneParserConfigObject(initial); @@ -9521,7 +9521,7 @@ function observeSerializedChatCompletionParserParams(body, initial, update) { delete snapshot.response_format; } update(snapshot); - root2 = void 0; + root = void 0; tools = void 0; responseFormat = void 0; responseFrame = void 0; @@ -9533,7 +9533,7 @@ function observeSerializedChatCompletionParserParams(body, initial, update) { }); } function finalizeChatCompletion(snapshot, params, audioDoneChoiceIndexes, validatedMessages) { - const { id, choices, created, model: model3, system_fingerprint, ...rest } = snapshot; + const { id, choices, created, model: model2, system_fingerprint, ...rest } = snapshot; const completion = { ...rest, id, @@ -9685,7 +9685,7 @@ function finalizeChatCompletion(snapshot, params, audioDoneChoiceIndexes, valida }; }), created, - model: model3, + model: model2, object: "chat.completion", // Spread creates an own data property without invoking inherited setters or changing the object prototype. ...system_fingerprint ? { system_fingerprint } : {} @@ -18282,8 +18282,8 @@ var init_models2 = __esm({ * Retrieves a model instance, providing basic information about the model such as * the owner and permissioning. */ - retrieve(model3, options) { - return this._client.get(path`/models/${model3}`, { ...options, __security: { bearerAuth: true } }); + retrieve(model2, options) { + return this._client.get(path`/models/${model2}`, { ...options, __security: { bearerAuth: true } }); } /** * Lists the currently available models, and provides basic information about each @@ -18296,8 +18296,8 @@ var init_models2 = __esm({ * Delete a fine-tuned model. You must have the Owner role in your organization to * delete a model. */ - delete(model3, options) { - return this._client.delete(path`/models/${model3}`, { ...options, __security: { bearerAuth: true } }); + delete(model2, options) { + return this._client.delete(path`/models/${model2}`, { ...options, __security: { bearerAuth: true } }); } }; } @@ -20943,8 +20943,8 @@ function selectMatchingSignature(signatureHeader, expectedSignature, firstSignat } return matchingSignature; } -async function verifyWebhookSignature(payload, signatureHeader, timestamp, webhookId, secret, tolerance) { - const timestampSeconds = Number.parseInt(timestamp, 10); +async function verifyWebhookSignature(payload, signatureHeader, timestamp2, webhookId, secret, tolerance) { + const timestampSeconds = Number.parseInt(timestamp2, 10); if (Number.isNaN(timestampSeconds)) { throw new InvalidWebhookSignatureError("Invalid webhook timestamp format"); } @@ -20961,7 +20961,7 @@ async function verifyWebhookSignature(payload, signatureHeader, timestamp, webho throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature"); } const decodedSecret = Uint8Array.from(secret.startsWith("whsec_") ? fromBase64(secret.slice("whsec_".length)) : encodeUTF8(secret)); - const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; + const signedPayload = webhookId ? `${webhookId}.${timestamp2}.${payload}` : `${timestamp2}.${payload}`; const signedPayloadBytes = Uint8Array.from(encodeUTF8(signedPayload)); const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, useBoundedVerification ? ["sign", "verify"] : ["verify"]); if (useBoundedVerification && firstSignature) { @@ -21177,12 +21177,12 @@ var init_webhooks = __esm({ __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); const headersObj = buildHeaders([headers]).values; const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature"); - const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp"); + const timestamp2 = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp"); const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id"); if (webhookSignatureRequiresSigning(signatureHeader) && typeof crypto.subtle.sign !== "function") { throw new Error("Webhook signature verification is only supported when the `crypto` global is defined"); } - return await verifyWebhookSignature(payload, signatureHeader, timestamp, webhookId, secret, tolerance); + return await verifyWebhookSignature(payload, signatureHeader, timestamp2, webhookId, secret, tolerance); } }; _Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret2(secret) { @@ -21759,17 +21759,17 @@ var init_client = __esm({ const request2 = authentication instanceof X509WorkloadIdentityAuth ? Promise.resolve(options).then((resolved) => authentication.runRequest(() => this.makeRequest(resolved, remainingRetries, void 0), this)) : this.makeRequest(options, remainingRetries, void 0); return this.responsePromise(request2); } - responsePromise(request2, parse = (client, props) => this.parseResponseWithTimeout(client, props)) { + responsePromise(request2, parse2 = (client, props) => this.parseResponseWithTimeout(client, props)) { const promise = new APIPromise(this, request2, (client, props) => { const resume = __classPrivateFieldGet(this, _OpenAI_responseAttempts, "f").get(props.controller)?.continueRequest; - return resume ? resume(() => parse(client, props)) : parse(client, props); + return resume ? resume(() => parse2(client, props)) : parse2(client, props); }); promise.withResponse = async () => { const data = await promise; const { response } = await request2; return { data, response, request_id: response.headers.get("x-request-id") }; }; - promise._thenUnwrap = (transform) => this.responsePromise(request2, async (client, props) => addRequestID(transform(await parse(client, props), props), props.response)); + promise._thenUnwrap = (transform) => this.responsePromise(request2, async (client, props) => addRequestID(transform(await parse2(client, props), props), props.response)); return promise; } async parseResponseWithTimeout(client, props) { @@ -22532,72 +22532,72 @@ var init_provider_env = __esm({ function isJsonSchemaObject(value2) { return typeof value2 === "object" && value2 !== null && !Array.isArray(value2); } -function isStructuredSchema(schema) { - if (!isJsonSchemaObject(schema)) +function isStructuredSchema(schema4) { + if (!isJsonSchemaObject(schema4)) return false; - const types = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : []; - return types.includes("object") || types.includes("array") || schema.properties !== void 0 || schema.items !== void 0; + const types = typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : []; + return types.includes("object") || types.includes("array") || schema4.properties !== void 0 || schema4.items !== void 0; } -function schemaAllowsNull(schema) { - if (!isJsonSchemaObject(schema)) +function schemaAllowsNull(schema4) { + if (!isJsonSchemaObject(schema4)) return false; - if (schema.type === "null" || Array.isArray(schema.type) && schema.type.includes("null")) + if (schema4.type === "null" || Array.isArray(schema4.type) && schema4.type.includes("null")) return true; - if (schema.const === null || Array.isArray(schema.enum) && schema.enum.includes(null)) + if (schema4.const === null || Array.isArray(schema4.enum) && schema4.enum.includes(null)) return true; - return Array.isArray(schema.anyOf) && schema.anyOf.some((variant) => schemaAllowsNull(variant)); + return Array.isArray(schema4.anyOf) && schema4.anyOf.some((variant) => schemaAllowsNull(variant)); } -function makeJsonSchemaNodeStrict(schema, isUnsupportedKeyword) { - if (!isJsonSchemaObject(schema)) { +function makeJsonSchemaNodeStrict(schema4, isUnsupportedKeyword) { + if (!isJsonSchemaObject(schema4)) { throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported"); } for (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) { - if (schema[key] !== void 0) { + if (schema4[key] !== void 0) { throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`); } } if (isUnsupportedKeyword) { - for (const [key, value2] of Object.entries(schema)) { + for (const [key, value2] of Object.entries(schema4)) { if (isUnsupportedKeyword(key, value2)) { throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value2)} is unsupported`); } } } - if (schema.anyOf !== void 0) { - if (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) { + if (schema4.anyOf !== void 0) { + if (!Array.isArray(schema4.anyOf) || schema4.anyOf.length === 0) { throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema"); } - for (const variant of schema.anyOf) { + for (const variant of schema4.anyOf) { if (isStructuredSchema(variant)) { throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported"); } makeJsonSchemaNodeStrict(variant, isUnsupportedKeyword); } } - if (schema.items !== void 0) { - if (Array.isArray(schema.items)) { + if (schema4.items !== void 0) { + if (Array.isArray(schema4.items)) { throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported"); } - makeJsonSchemaNodeStrict(schema.items, isUnsupportedKeyword); + makeJsonSchemaNodeStrict(schema4.items, isUnsupportedKeyword); } - const isObjectSchema = schema.type === "object"; - if (schema.properties !== void 0 && !isObjectSchema) { + const isObjectSchema = schema4.type === "object"; + if (schema4.properties !== void 0 && !isObjectSchema) { throw new UnsupportedStrictJsonSchemaError("properties require type object"); } if (!isObjectSchema) return; - if (schema.additionalProperties !== void 0 && schema.additionalProperties !== false) { + if (schema4.additionalProperties !== void 0 && schema4.additionalProperties !== false) { throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported"); } - if (schema.properties !== void 0 && !isJsonSchemaObject(schema.properties)) { + if (schema4.properties !== void 0 && !isJsonSchemaObject(schema4.properties)) { throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map"); } - if (schema.required !== void 0 && (!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== "string"))) { + if (schema4.required !== void 0 && (!Array.isArray(schema4.required) || schema4.required.some((key) => typeof key !== "string"))) { throw new UnsupportedStrictJsonSchemaError("object required must be a string array"); } - const properties = schema.properties ?? {}; + const properties = schema4.properties ?? {}; const propertyNames = Object.keys(properties); - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); if ([...required].some((key) => !propertyNames.includes(key))) { throw new UnsupportedStrictJsonSchemaError("required contains an unknown property"); } @@ -22607,11 +22607,11 @@ function makeJsonSchemaNodeStrict(schema, isUnsupportedKeyword) { properties[key] = { anyOf: [property, { type: "null" }] }; } } - schema.required = propertyNames; - schema.additionalProperties = false; + schema4.required = propertyNames; + schema4.additionalProperties = false; } -function makeStrictJsonSchema(schema, isUnsupportedKeyword) { - const cloned = structuredClone(schema); +function makeStrictJsonSchema(schema4, isUnsupportedKeyword) { + const cloned = structuredClone(schema4); if (!isJsonSchemaObject(cloned)) { throw new UnsupportedStrictJsonSchemaError("root schema must have type object"); } @@ -22669,18 +22669,18 @@ function grammarToolInputJsonStart(buffer, inputProperty) { return `{${JSON.stringify(inputProperty)}:"`; } function inferGrammarInputProperty(tool) { - const schema = tool.parameters; - if (schema.type !== "object") { + const schema4 = tool.parameters; + if (schema4.type !== "object") { throw new Error("grammar constrained sampling requires an object parameter schema"); } - if (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== "string") { + if (!Array.isArray(schema4.required) || schema4.required.length !== 1 || typeof schema4.required[0] !== "string") { throw new Error("grammar constrained sampling requires exactly one required string property"); } - const inputProperty = schema.required[0]; - if (!schema.properties?.[inputProperty]) { + const inputProperty = schema4.required[0]; + if (!schema4.properties?.[inputProperty]) { throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`); } - if (schema.properties[inputProperty]?.type !== "string") { + if (schema4.properties[inputProperty]?.type !== "string") { throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`); } return inputProperty; @@ -23078,8 +23078,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON2; - exports.parse = parse; + var parse2 = parseJSON2; + exports.parse = parse2; } }); @@ -23679,8 +23679,8 @@ function replaceImagesWithPlaceholder(content, placeholder) { } return result; } -function downgradeUnsupportedImages(messages, model3) { - if (model3.input.includes("image")) { +function downgradeUnsupportedImages(messages, model2) { + if (model2.input.includes("image")) { return messages; } return messages.map((msg) => { @@ -23699,10 +23699,10 @@ function downgradeUnsupportedImages(messages, model3) { return msg; }); } -function transformMessages(messages, model3, normalizeToolCallId2) { +function transformMessages(messages, model2, normalizeToolCallId2) { const toolCallIdMap = /* @__PURE__ */ new Map(); const normalizedMessages = messages.map((msg) => msg.content == null ? { ...msg, content: [] } : msg); - const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model3); + const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model2); const transformed = imageAwareMessages.map((msg) => { if (msg.role === "system" || msg.role === "user") { return msg; @@ -23716,7 +23716,7 @@ function transformMessages(messages, model3, normalizeToolCallId2) { } if (msg.role === "assistant") { const assistantMsg = msg; - const isSameModel = assistantMsg.provider === model3.provider && assistantMsg.api === model3.api && assistantMsg.model === model3.id; + const isSameModel = assistantMsg.provider === model2.provider && assistantMsg.api === model2.api && assistantMsg.model === model2.id; const transformedContent = assistantMsg.content.flatMap((block) => { if (block.type === "thinking") { if (!isSameModel) @@ -23743,7 +23743,7 @@ function transformMessages(messages, model3, normalizeToolCallId2) { delete normalizedToolCall.thoughtSignature; } if (!isSameModel && normalizeToolCallId2) { - const normalizedId = normalizeToolCallId2(toolCall.id, model3, assistantMsg); + const normalizedId = normalizeToolCallId2(toolCall.id, model2, assistantMsg); if (normalizedId !== toolCall.id) { toolCallIdMap.set(toolCall.id, normalizedId); normalizedToolCall = { ...normalizedToolCall, id: normalizedId }; @@ -23850,11 +23850,11 @@ function parseTextSignature(signature) { } return { id: signature }; } -function convertToolResultOutput(model3, content) { +function convertToolResultOutput(model2, content) { const textResult = content.filter((c) => c.type === "text").map((c) => c.text).join("\n"); const images = content.filter((c) => c.type === "image"); const hasText = textResult.trim().length > 0; - if (images.length === 0 || !model3.input.includes("image")) { + if (images.length === 0 || !model2.input.includes("image")) { return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? "(see attached image)" : "(no tool output)"); } const output = []; @@ -23884,7 +23884,7 @@ function renderToolRemovalNotice(names2) { return `The following tools are no longer available. Do not call them: ${names2.map((name) => `- ${name}`).join("\n")}`; } -function convertResponsesMessages(model3, context, allowedToolCallProviders, options) { +function convertResponsesMessages(model2, context, allowedToolCallProviders, options) { const normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages); const messages = []; const normalizeIdPart = (part) => { @@ -23897,20 +23897,20 @@ function convertResponsesMessages(model3, context, allowedToolCallProviders, opt return normalized.length > 64 ? normalized.slice(0, 64) : normalized; }; const normalizeToolCallId2 = (id, _targetModel, source) => { - if (!allowedToolCallProviders.has(model3.provider)) + if (!allowedToolCallProviders.has(model2.provider)) return normalizeIdPart(id); if (!id.includes("|")) return normalizeIdPart(id); const [callId, itemId] = id.split("|"); const normalizedCallId = normalizeIdPart(callId); - const isForeignToolCall = source.provider !== model3.provider || source.api !== model3.api; + const isForeignToolCall = source.provider !== model2.provider || source.api !== model2.api; let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId); if (!normalizedItemId.startsWith("fc_")) { normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`); } return `${normalizedCallId}|${normalizedItemId}`; }; - const transformedMessages = transformMessages(normalizedContext.messages, model3, normalizeToolCallId2); + const transformedMessages = transformMessages(normalizedContext.messages, model2, normalizeToolCallId2); const toolSupport = getResponsesToolSupport(options ?? {}); const transcriptTools = resolveTranscriptTools(normalizedContext.messages, toolSupport); let declaredAdditionalTools = false; @@ -23959,8 +23959,8 @@ function convertResponsesMessages(model3, context, allowedToolCallProviders, opt reasoning: { effort } }); }; - const compat = model3.compat; - const instructionRole = model3.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system"; + const compat = model2.compat; + const instructionRole = model2.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system"; let msgIndex = 0; let sourceIndex = 0; let systemIndex = 0; @@ -24015,9 +24015,9 @@ function convertResponsesMessages(model3, context, allowedToolCallProviders, opt } else if (msg.role === "assistant") { const output = []; const assistantMsg = msg; - const isSameProviderAndApi = assistantMsg.provider === model3.provider && assistantMsg.api === model3.api; - const isSameModel = isSameProviderAndApi && assistantMsg.model === model3.id; - const isDifferentModel = isSameProviderAndApi && assistantMsg.model !== model3.id; + const isSameProviderAndApi = assistantMsg.provider === model2.provider && assistantMsg.api === model2.api; + const isSameModel = isSameProviderAndApi && assistantMsg.model === model2.id; + const isDifferentModel = isSameProviderAndApi && assistantMsg.model !== model2.id; let textBlockIndex = 0; for (const block of msg.content) { if (block.type === "thinking") { @@ -24082,7 +24082,7 @@ function convertResponsesMessages(model3, context, allowedToolCallProviders, opt messages.push(...output); } else if (msg.role === "toolResult") { const [callId] = msg.toolCallId.split("|"); - const output = convertToolResultOutput(model3, msg.content); + const output = convertToolResultOutput(model2, msg.content); if (options?.grammarToolInputProperties?.has(msg.toolName)) { messages.push({ type: "custom_tool_call_output", @@ -24138,7 +24138,7 @@ function convertResponsesTools(tools, options) { return functionTool; }); } -async function processResponsesStream(openaiStream, output, stream4, model3, options) { +async function processResponsesStream(openaiStream, output, stream4, model2, options) { let sawTerminalResponseEvent = false; const outputSlots = /* @__PURE__ */ new Map(); const unfinishedToolCalls = /* @__PURE__ */ new Set(); @@ -24269,7 +24269,7 @@ async function processResponsesStream(openaiStream, output, stream4, model3, opt cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }; } - calculateCost(model3, output.usage); + calculateCost(model2, output.usage); if (options?.applyServiceTierPricing) { const serviceTier = options.resolveServiceTier ? options.resolveServiceTier(response?.service_tier, options.serviceTier) : response?.service_tier ?? options.serviceTier; options.applyServiceTierPricing(output.usage, serviceTier); @@ -24289,7 +24289,7 @@ async function processResponsesStream(openaiStream, output, stream4, model3, opt } }; for await (const event of openaiStream) { - await options?.onProviderStreamEvent?.(event, model3); + await options?.onProviderStreamEvent?.(event, model2); if (event.type === "response.created") { output.responseId = event.response.id; } else if (event.type === "response.output_item.added") { @@ -24604,23 +24604,23 @@ var init_estimate = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/api/simple-options.js -function clampMaxTokensToContext(model3, context, maxTokens) { - if (model3.contextWindow <= 0) +function clampMaxTokensToContext(model2, context, maxTokens) { + if (model2.contextWindow <= 0) return Math.max(MIN_MAX_TOKENS, maxTokens); - const available = model3.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS; + const available = model2.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS; return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available)); } -function resolveSamplingParams(model3, thinkingLevel, requestParams) { - const effectiveThinkingLevel = clampThinkingLevel(model3, thinkingLevel); - const thinkingLevelParams = model3.samplingParamsByThinkingLevel?.[effectiveThinkingLevel]; - return model3.samplingParams || thinkingLevelParams || requestParams ? { ...model3.samplingParams, ...thinkingLevelParams, ...requestParams } : void 0; +function resolveSamplingParams(model2, thinkingLevel, requestParams) { + const effectiveThinkingLevel = clampThinkingLevel(model2, thinkingLevel); + const thinkingLevelParams = model2.samplingParamsByThinkingLevel?.[effectiveThinkingLevel]; + return model2.samplingParams || thinkingLevelParams || requestParams ? { ...model2.samplingParams, ...thinkingLevelParams, ...requestParams } : void 0; } -function buildBaseOptions(model3, context, options, apiKey) { - const samplingParams = resolveSamplingParams(model3, options?.reasoning ?? "off", options?.samplingParams); +function buildBaseOptions(model2, context, options, apiKey) { + const samplingParams = resolveSamplingParams(model2, options?.reasoning ?? "off", options?.samplingParams); return { temperature: options?.temperature, samplingParams, - maxTokens: clampMaxTokensToContext(model3, context, options?.maxTokens ?? model3.maxTokens), + maxTokens: clampMaxTokensToContext(model2, context, options?.maxTokens ?? model2.maxTokens), signal: options?.signal, telemetry: options?.telemetry, apiKey: apiKey || options?.apiKey, @@ -24683,8 +24683,8 @@ __export(openai_responses_exports, { stream: () => stream, streamSimple: () => streamSimple }); -function isChatGPTSignIn(model3, apiKey) { - return model3.provider === "openai" && model3.baseUrl === "https://api.openai.com/v1" && apiKey !== void 0 && !apiKey.startsWith("sk-"); +function isChatGPTSignIn(model2, apiKey) { + return model2.provider === "openai" && model2.baseUrl === "https://api.openai.com/v1" && apiKey !== void 0 && !apiKey.startsWith("sk-"); } function hasHeader(headers, name) { if (!headers) @@ -24703,8 +24703,8 @@ function getClientApiKey(provider2, apiKey, headers) { return "unused"; throw new Error(`No API key for provider: ${provider2}`); } -function detectSessionAffinityFormat(model3) { - return model3.provider === "openrouter" || model3.baseUrl.includes("openrouter.ai") ? "openrouter" : "openai"; +function detectSessionAffinityFormat(model2) { + return model2.provider === "openrouter" || model2.baseUrl.includes("openrouter.ai") ? "openrouter" : "openai"; } function resolveCacheRetention(cacheRetention, env) { if (cacheRetention) { @@ -24715,27 +24715,27 @@ function resolveCacheRetention(cacheRetention, env) { } return "short"; } -function getCompat(model3) { +function getCompat(model2) { return { - supportsDeveloperRole: model3.compat?.supportsDeveloperRole ?? true, - supportsMidConvoSystemMessages: model3.compat?.supportsMidConvoSystemMessages ?? false, - sessionAffinityFormat: model3.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model3), - supportsLongCacheRetention: model3.compat?.supportsLongCacheRetention ?? true, - supportsStrictMode: model3.compat?.supportsStrictMode ?? false, - supportsOpenAIGrammarTools: model3.compat?.supportsOpenAIGrammarTools ?? false, - supportsAdditionalTools: model3.compat?.supportsAdditionalTools ?? false, - supportsToolSearch: model3.compat?.supportsToolSearch ?? false, - supportsExplicitPromptCacheMode: model3.compat?.supportsExplicitPromptCacheMode ?? false, - supportsMaxOutputTokens: model3.compat?.supportsMaxOutputTokens ?? true, - supportsMidConvoEffort: model3.compat?.supportsMidConvoEffort ?? false + supportsDeveloperRole: model2.compat?.supportsDeveloperRole ?? true, + supportsMidConvoSystemMessages: model2.compat?.supportsMidConvoSystemMessages ?? false, + sessionAffinityFormat: model2.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model2), + supportsLongCacheRetention: model2.compat?.supportsLongCacheRetention ?? true, + supportsStrictMode: model2.compat?.supportsStrictMode ?? false, + supportsOpenAIGrammarTools: model2.compat?.supportsOpenAIGrammarTools ?? false, + supportsAdditionalTools: model2.compat?.supportsAdditionalTools ?? false, + supportsToolSearch: model2.compat?.supportsToolSearch ?? false, + supportsExplicitPromptCacheMode: model2.compat?.supportsExplicitPromptCacheMode ?? false, + supportsMaxOutputTokens: model2.compat?.supportsMaxOutputTokens ?? true, + supportsMidConvoEffort: model2.compat?.supportsMidConvoEffort ?? false }; } -function getConfigurationUpdateEffort(model3, options, compat) { +function getConfigurationUpdateEffort(model2, options, compat) { if (!compat.supportsMidConvoEffort || !options?.reasoningEffort || // Sign in with ChatGPT rejects configuration_update items. - isChatGPTSignIn(model3, options.apiKey)) { + isChatGPTSignIn(model2, options.apiKey)) { return void 0; } - return model3.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort; + return model2.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort; } function getPromptCacheRetention(compat, cacheRetention) { return cacheRetention === "long" && compat.supportsLongCacheRetention && !compat.supportsExplicitPromptCacheMode ? "24h" : void 0; @@ -24749,10 +24749,10 @@ function getPromptCacheOptions(compat, cacheRetention) { return { ttl: "30m" }; return void 0; } -function createClient(model3, context, apiKey, optionsHeaders, identity, fetch2, sessionId) { - const compat = getCompat(model3); - const headers = { ...getIdentityHeaders(model3, identity), ...model3.headers }; - if (model3.provider === "github-copilot") { +function createClient(model2, context, apiKey, optionsHeaders, identity, fetch2, sessionId) { + const compat = getCompat(model2); + const headers = { ...getIdentityHeaders(model2, identity), ...model2.headers }; + if (model2.provider === "github-copilot") { const hasImages = hasCopilotVisionInput(context.messages); const copilotHeaders = buildCopilotDynamicHeaders({ messages: context.messages, @@ -24775,15 +24775,15 @@ function createClient(model3, context, apiKey, optionsHeaders, identity, fetch2, } return new OpenAI({ apiKey, - baseURL: model3.baseUrl, + baseURL: model2.baseUrl, dangerouslyAllowBrowser: true, fetch: fetch2, defaultHeaders: headers }); } -function buildParams(model3, context, options, compat, grammarToolInputProperties, configurationUpdateEffort) { +function buildParams(model2, context, options, compat, grammarToolInputProperties, configurationUpdateEffort) { const transcriptTools = resolveTranscriptTools(context.messages, getResponsesToolSupport(compat)); - const messages = convertResponsesMessages(model3, context, OPENAI_TOOL_CALL_PROVIDERS, { + const messages = convertResponsesMessages(model2, context, OPENAI_TOOL_CALL_PROVIDERS, { grammarToolInputProperties, supportsMidConvoSystemMessages: compat.supportsMidConvoSystemMessages, supportsAdditionalTools: compat.supportsAdditionalTools, @@ -24795,9 +24795,9 @@ function buildParams(model3, context, options, compat, grammarToolInputPropertie configurationUpdateEffort }); const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env); - const omitUnsupportedFields = isChatGPTSignIn(model3, options?.apiKey); + const omitUnsupportedFields = isChatGPTSignIn(model2, options?.apiKey); const params = { - model: model3.id, + model: model2.id, input: messages, stream: true, prompt_cache_key: cacheRetention === "none" ? void 0 : clampOpenAIPromptCacheKey(options?.sessionId), @@ -24824,42 +24824,42 @@ function buildParams(model3, context, options, compat, grammarToolInputPropertie params.tool_choice = options.toolChoice; } const reasoningEffort = options?.reasoningEffort ?? (options?.reasoningSummary ? "medium" : void 0); - if (model3.reasoning) { + if (model2.reasoning) { if (reasoningEffort) { - const requestedEffort = options?.reasoningEffort ? model3.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort : reasoningEffort; + const requestedEffort = options?.reasoningEffort ? model2.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort : reasoningEffort; const effort = configurationUpdateEffort === void 0 ? requestedEffort : CONFIGURATION_UPDATE_REQUEST_EFFORT; params.reasoning = { effort, summary: options?.reasoningSummary || "auto" }; params.include = ["reasoning.encrypted_content"]; - } else if (model3.provider !== "github-copilot" && model3.thinkingLevelMap?.off !== null) { + } else if (model2.provider !== "github-copilot" && model2.thinkingLevelMap?.off !== null) { params.reasoning = { - effort: model3.thinkingLevelMap?.off ?? "none" + effort: model2.thinkingLevelMap?.off ?? "none" }; } - if (model3.provider === "xai") + if (model2.provider === "xai") params.include = ["reasoning.encrypted_content"]; } - const samplingParams = resolveSamplingParams(model3, reasoningEffort ?? "off", options?.samplingParams); + const samplingParams = resolveSamplingParams(model2, reasoningEffort ?? "off", options?.samplingParams); if (samplingParams) { Object.assign(params, samplingParams); } return params; } -function getServiceTierCostMultiplier(model3, serviceTier) { +function getServiceTierCostMultiplier(model2, serviceTier) { switch (serviceTier) { case "flex": return 0.5; case "priority": case "fast": - return model3.id === "gpt-5.5" ? 2.5 : 2; + return model2.id === "gpt-5.5" ? 2.5 : 2; default: return 1; } } -function applyServiceTierPricing(usage, serviceTier, model3) { - const multiplier = getServiceTierCostMultiplier(model3, serviceTier); +function applyServiceTierPricing(usage, serviceTier, model2) { + const multiplier = getServiceTierCostMultiplier(model2, serviceTier); if (multiplier === 1) return; usage.cost.input *= multiplier; @@ -24890,18 +24890,18 @@ var init_openai_responses = __esm({ CHATGPT_USAGE_URL = "https://chatgpt.com/settings/usage"; CHATGPT_WORKSPACE_LIMIT_HINT = "You've reached your ChatGPT workspace's usage limit. Ask your workspace admin to increase it at admin.openai.com \u2192 Workspace \u2192 Usage limits."; CONFIGURATION_UPDATE_REQUEST_EFFORT = "medium"; - stream = (model3, context, options) => { + stream = (model2, context, options) => { const stream4 = new AssistantMessageEventStream(); - const normalizedContext = resolveTranscript(context, getCompat(model3).supportsMidConvoSystemMessages); + const normalizedContext = resolveTranscript(context, getCompat(model2).supportsMidConvoSystemMessages); (async () => { - const compat = getCompat(model3); - const configurationUpdateEffort = getConfigurationUpdateEffort(model3, options, compat); + const compat = getCompat(model2); + const configurationUpdateEffort = getConfigurationUpdateEffort(model2, options, compat); const output = { role: "assistant", content: [], - api: model3.api, - provider: model3.provider, - model: model3.id, + api: model2.api, + provider: model2.provider, + model: model2.id, ...configurationUpdateEffort === void 0 ? {} : { providerThinkingLevel: configurationUpdateEffort }, usage: { input: 0, @@ -24915,13 +24915,13 @@ var init_openai_responses = __esm({ timestamp: Date.now() }; try { - const apiKey = getClientApiKey(model3.provider, options?.apiKey, options?.headers); + const apiKey = getClientApiKey(model2.provider, options?.apiKey, options?.headers); const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env); const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId; const grammarToolInputProperties = createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages), compat.supportsOpenAIGrammarTools); - const client = createClient(model3, normalizedContext, apiKey, options?.headers, options?.identity, options?.fetch, cacheSessionId); - let params = buildParams(model3, normalizedContext, options, compat, grammarToolInputProperties, configurationUpdateEffort); - const nextParams = await options?.onPayload?.(params, model3); + const client = createClient(model2, normalizedContext, apiKey, options?.headers, options?.identity, options?.fetch, cacheSessionId); + let params = buildParams(model2, normalizedContext, options, compat, grammarToolInputProperties, configurationUpdateEffort); + const nextParams = await options?.onPayload?.(params, model2); if (nextParams !== void 0) { params = nextParams; } @@ -24935,13 +24935,13 @@ var init_openai_responses = __esm({ maxRetryDelayMs: options?.maxRetryDelayMs, signal: options?.signal }); - await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model3); + await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model2); stream4.push({ type: "start", partial: output }); - await processResponsesStream(openaiStream, output, stream4, model3, { + await processResponsesStream(openaiStream, output, stream4, model2, { onProviderStreamEvent: options?.onProviderStreamEvent, serviceTier: options?.serviceTier, grammarToolInputProperties, - applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model3) + applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model2) }); if (options?.signal?.aborted) { throw new Error("Request was aborted"); @@ -24956,7 +24956,7 @@ var init_openai_responses = __esm({ stream4.end(); } catch (error) { output.stopReason = options?.signal?.aborted ? "aborted" : "error"; - const errorMessage3 = formatProviderError(normalizeProviderError(error), `${model3.provider === "openai" ? "OpenAI" : model3.provider} API error`); + const errorMessage3 = formatProviderError(normalizeProviderError(error), `${model2.provider === "openai" ? "OpenAI" : model2.provider} API error`); if (errorMessage3.includes("subscription_sharing_usage_limit_exceeded")) { output.errorMessage = `${errorMessage3} Check your ChatGPT usage: ${CHATGPT_USAGE_URL}`; @@ -24972,15 +24972,15 @@ ${CHATGPT_WORKSPACE_LIMIT_HINT}`; })(); return stream4; }; - streamSimple = (model3, context, options) => { - getClientApiKey(model3.provider, options?.apiKey, options?.headers); + streamSimple = (model2, context, options) => { + getClientApiKey(model2.provider, options?.apiKey, options?.headers); const base = { - ...buildBaseOptions(model3, context, options, options?.apiKey), + ...buildBaseOptions(model2, context, options, options?.apiKey), toolChoice: options?.toolChoice }; - const clampedReasoning = options?.reasoning ? clampThinkingLevel(model3, options.reasoning) : void 0; + const clampedReasoning = options?.reasoning ? clampThinkingLevel(model2, options.reasoning) : void 0; const reasoningEffort = clampedReasoning === "off" ? void 0 : clampedReasoning; - return stream(model3, context, { + return stream(model2, context, { ...base, reasoningEffort }); @@ -25541,20 +25541,20 @@ var init_utils3 = __esm({ if (str2.length === 0) { return str2; } - let string = str2; + let string2 = str2; if (typeof str2 === "symbol") { - string = Symbol.prototype.toString.call(str2); + string2 = Symbol.prototype.toString.call(str2); } else if (typeof str2 !== "string") { - string = String(str2); + string2 = String(str2); } if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) { return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; }); } let out = ""; - for (let j = 0; j < string.length; j += limit2) { - const segment = string.length >= limit2 ? string.slice(j, j + limit2) : string; + for (let j = 0; j < string2.length; j += limit2) { + const segment = string2.length >= limit2 ? string2.slice(j, j + limit2) : string2; const arr2 = []; for (let i = 0; i < segment.length; ++i) { let c = segment.charCodeAt(i); @@ -29026,7 +29026,7 @@ var require_base64 = __commonJS({ // node_modules/fast-sha256/sha256.js var require_sha256 = __commonJS({ "node_modules/fast-sha256/sha256.js"(exports, module) { - (function(root2, factory) { + (function(root, factory) { var exports2 = {}; factory(exports2); var sha256 = exports2["default"]; @@ -29040,7 +29040,7 @@ var require_sha256 = __commonJS({ return sha256; }); } else { - root2.sha256 = sha256; + root.sha256 = sha256; } })(exports, function(exports2) { "use strict"; @@ -29541,8 +29541,8 @@ var require_dist2 = __commonJS({ if (!msgSignature || !msgId || !msgTimestamp) { throw new WebhookVerificationError("Missing required headers"); } - const timestamp = this.verifyTimestamp(msgTimestamp); - const computedSignature = this.sign(msgId, timestamp, payload); + const timestamp2 = this.verifyTimestamp(msgTimestamp); + const computedSignature = this.sign(msgId, timestamp2, payload); const expectedSignature = computedSignature.split(",")[1]; const passedSignatures = msgSignature.split(" "); const encoder6 = new globalThis.TextEncoder(); @@ -29565,7 +29565,7 @@ var require_dist2 = __commonJS({ } throw new WebhookVerificationError("No matching signature found"); } - sign(msgId, timestamp, payload) { + sign(msgId, timestamp2, payload) { if (typeof payload === "string") { } else if (payload.constructor.name === "Buffer") { payload = payload.toString(); @@ -29573,24 +29573,24 @@ var require_dist2 = __commonJS({ throw new Error("Expected payload to be of type string or Buffer."); } const encoder6 = new TextEncoder(); - const timestampNumber = Math.floor(timestamp.getTime() / 1e3); + const timestampNumber = Math.floor(timestamp2.getTime() / 1e3); const toSign = encoder6.encode(`${msgId}.${timestampNumber}.${payload}`); const expectedSignature = base64.encode(sha256.hmac(this.key, toSign)); return `v1,${expectedSignature}`; } verifyTimestamp(timestampHeader) { const now = Math.floor(Date.now() / 1e3); - const timestamp = parseInt(timestampHeader, 10); - if (Number.isNaN(timestamp)) { + const timestamp2 = parseInt(timestampHeader, 10); + if (Number.isNaN(timestamp2)) { throw new WebhookVerificationError("Invalid Signature Headers"); } - if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) { + if (now - timestamp2 > WEBHOOK_TOLERANCE_IN_SECONDS) { throw new WebhookVerificationError("Message timestamp too old"); } - if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) { + if (timestamp2 > now + WEBHOOK_TOLERANCE_IN_SECONDS) { throw new WebhookVerificationError("Message timestamp too new"); } - return new Date(timestamp * 1e3); + return new Date(timestamp2 * 1e3); } }; exports.Webhook = Webhook2; @@ -34189,7 +34189,7 @@ var init_BetaToolRunner = __esm({ } let definition = change.tool; if ("run" in change.tool) { - const { run: run2, parse, close, ...rest } = change.tool; + const { run: run2, parse: parse2, close, ...rest } = change.tool; definition = rest; } content.push({ type: "tool_addition", tool: { type: "tool_definition", definition } }); @@ -40049,8 +40049,8 @@ var init_env_api_keys = __esm({ function isValidCost(value2) { return typeof value2 === "number" && Number.isFinite(value2) && value2 >= 0; } -function isOpenRouterModel(model3) { - return model3.provider === "openrouter" || model3.baseUrl.includes("openrouter.ai"); +function isOpenRouterModel(model2) { + return model2.provider === "openrouter" || model2.baseUrl.includes("openrouter.ai"); } function applyOpenRouterReportedCost(usage, reported) { if (!isValidCost(reported.cost)) @@ -40097,12 +40097,12 @@ function resolveCacheRetention2(cacheRetention, env) { } return "short"; } -function getCacheControl(model3, cacheRetention, env) { +function getCacheControl(model2, cacheRetention, env) { const retention = resolveCacheRetention2(cacheRetention, env); if (retention === "none") { return { retention }; } - const ttl = retention === "long" && getAnthropicCompat(model3).supportsLongCacheRetention ? "1h" : void 0; + const ttl = retention === "long" && getAnthropicCompat(model2).supportsLongCacheRetention ? "1h" : void 0; return { retention, cacheControl: { type: "ephemeral", ...ttl && { ttl } } @@ -40141,22 +40141,22 @@ function convertContentBlocks(content) { } return blocks; } -function shouldUseServerSideFallbackBeta(model3) { - return (model3.compat?.allowedFallbackModels?.length ?? 0) > 0; +function shouldUseServerSideFallbackBeta(model2) { + return (model2.compat?.allowedFallbackModels?.length ?? 0) > 0; } -function getAnthropicCompat(model3) { - const isOpenRouter2 = model3.provider === "openrouter" || model3.baseUrl.includes("openrouter.ai"); +function getAnthropicCompat(model2) { + const isOpenRouter2 = model2.provider === "openrouter" || model2.baseUrl.includes("openrouter.ai"); return { - supportsEagerToolInputStreaming: model3.compat?.supportsEagerToolInputStreaming ?? true, - supportsLongCacheRetention: model3.compat?.supportsLongCacheRetention ?? true, - sendSessionAffinityHeaders: model3.compat?.sendSessionAffinityHeaders ?? isOpenRouter2, - sessionAffinityFormat: model3.compat?.sessionAffinityFormat ?? (isOpenRouter2 ? "openrouter" : void 0), - supportsCacheControlOnTools: model3.compat?.supportsCacheControlOnTools ?? true, - supportsTemperature: model3.compat?.supportsTemperature ?? true, - allowEmptySignature: model3.compat?.allowEmptySignature ?? false, - supportsStrictTools: model3.compat?.supportsStrictTools ?? false, - supportsMidConvoSystemMessages: model3.compat?.supportsMidConvoSystemMessages ?? false, - supportsMidConvoToolChanges: model3.compat?.supportsMidConvoToolChanges ?? false + supportsEagerToolInputStreaming: model2.compat?.supportsEagerToolInputStreaming ?? true, + supportsLongCacheRetention: model2.compat?.supportsLongCacheRetention ?? true, + sendSessionAffinityHeaders: model2.compat?.sendSessionAffinityHeaders ?? isOpenRouter2, + sessionAffinityFormat: model2.compat?.sessionAffinityFormat ?? (isOpenRouter2 ? "openrouter" : void 0), + supportsCacheControlOnTools: model2.compat?.supportsCacheControlOnTools ?? true, + supportsTemperature: model2.compat?.supportsTemperature ?? true, + allowEmptySignature: model2.compat?.allowEmptySignature ?? false, + supportsStrictTools: model2.compat?.supportsStrictTools ?? false, + supportsMidConvoSystemMessages: model2.compat?.supportsMidConvoSystemMessages ?? false, + supportsMidConvoToolChanges: model2.compat?.supportsMidConvoToolChanges ?? false }; } function mergeHeaders2(...headerSources) { @@ -40185,8 +40185,8 @@ function assertRequestAuth(provider2, apiKey, headers) { if (!hasRequestAuth(apiKey, headers)) throw new Error(`No API key for provider: ${provider2}`); } -function getAnthropicFederation(model3, apiKey, headers, env) { - if (model3.provider !== "anthropic" || hasRequestAuth(apiKey, headers)) +function getAnthropicFederation(model2, apiKey, headers, env) { + if (model2.provider !== "anthropic" || hasRequestAuth(apiKey, headers)) return void 0; const federationRuleId = getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV, env); const organizationId = getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV, env); @@ -40343,8 +40343,8 @@ async function* iterateAnthropicEvents(response, signal) { throw new Error("Anthropic stream ended before message_stop"); } } -function mapThinkingLevelToEffort(model3, level) { - const mapped = level ? model3.thinkingLevelMap?.[level] : void 0; +function mapThinkingLevelToEffort(model2, level) { + const mapped = level ? model2.thinkingLevelMap?.[level] : void 0; if (typeof mapped === "string") return mapped; switch (level) { @@ -40362,18 +40362,18 @@ function mapThinkingLevelToEffort(model3, level) { function isOAuthToken(apiKey) { return apiKey.includes("sk-ant-oat"); } -function createClient2(model3, apiKey, optionsHeaders, fetch2, dynamicHeaders, sessionId, federation, identity) { - if (model3.provider === "github-copilot") { +function createClient2(model2, apiKey, optionsHeaders, fetch2, dynamicHeaders, sessionId, federation, identity) { + if (model2.provider === "github-copilot") { const client2 = new PiAnthropic({ apiKey: null, authToken: apiKey ?? null, - baseURL: model3.baseUrl, + baseURL: model2.baseUrl, dangerouslyAllowBrowser: true, fetch: fetch2, - defaultHeaders: mergeHeaders2(getIdentityHeaders(model3, identity), { + defaultHeaders: mergeHeaders2(getIdentityHeaders(model2, identity), { accept: "application/json", "anthropic-dangerous-direct-browser-access": "true" - }, model3.headers, dynamicHeaders, optionsHeaders) + }, model2.headers, dynamicHeaders, optionsHeaders) }); return { client: client2, isOAuthToken: false }; } @@ -40381,7 +40381,7 @@ function createClient2(model3, apiKey, optionsHeaders, fetch2, dynamicHeaders, s const client2 = new PiAnthropic({ apiKey: null, authToken: apiKey, - baseURL: model3.baseUrl, + baseURL: model2.baseUrl, dangerouslyAllowBrowser: true, fetch: fetch2, defaultHeaders: mergeHeaders2({ @@ -40389,28 +40389,28 @@ function createClient2(model3, apiKey, optionsHeaders, fetch2, dynamicHeaders, s "anthropic-dangerous-direct-browser-access": "true", "user-agent": `claude-cli/${claudeCodeVersion}`, "x-app": "cli" - }, model3.headers, optionsHeaders) + }, model2.headers, optionsHeaders) }); return { client: client2, isOAuthToken: true }; } - const compat = getAnthropicCompat(model3); + const compat = getAnthropicCompat(model2); const sessionAffinityHeaders = {}; if (sessionId && compat.sendSessionAffinityHeaders) { const header = compat.sessionAffinityFormat === "openrouter" ? "x-session-id" : "x-session-affinity"; sessionAffinityHeaders[header] = sessionId; } - const defaultHeaders = mergeHeaders2(getIdentityHeaders(model3, identity), { + const defaultHeaders = mergeHeaders2(getIdentityHeaders(model2, identity), { accept: "application/json", "anthropic-dangerous-direct-browser-access": "true" - }, sessionAffinityHeaders, model3.headers, optionsHeaders); + }, sessionAffinityHeaders, model2.headers, optionsHeaders); if (federation) { - const key = JSON.stringify([model3.baseUrl, federation]); + const key = JSON.stringify([model2.baseUrl, federation]); if (federationClient?.key !== key || federationClient.fetch !== fetch2) { const client2 = new PiAnthropic({ apiKey: null, authToken: null, config: federation, - baseURL: model3.baseUrl, + baseURL: model2.baseUrl, dangerouslyAllowBrowser: true, fetch: fetch2 }); @@ -40421,16 +40421,16 @@ function createClient2(model3, apiKey, optionsHeaders, fetch2, dynamicHeaders, s const client = new PiAnthropic({ apiKey: apiKey ?? null, authToken: null, - baseURL: model3.baseUrl, + baseURL: model2.baseUrl, dangerouslyAllowBrowser: true, fetch: fetch2, defaultHeaders }); return { client, isOAuthToken: false }; } -function getBetaFeatures(model3, context, isOAuthToken2, nativeToolChanges, options) { +function getBetaFeatures(model2, context, isOAuthToken2, nativeToolChanges, options) { let configuredFeatures; - for (const headers of [model3.headers, options?.headers]) { + for (const headers of [model2.headers, options?.headers]) { for (const [name, value2] of Object.entries(headers ?? {})) { if (name.toLowerCase() === "anthropic-beta") configuredFeatures = value2; @@ -40446,26 +40446,26 @@ function getBetaFeatures(model3, context, isOAuthToken2, nativeToolChanges, opti const features = []; if (isOAuthToken2) features.push("claude-code-20250219", "oauth-2025-04-20"); - if (shouldUseFineGrainedToolStreamingBeta(model3, context)) + if (shouldUseFineGrainedToolStreamingBeta(model2, context)) features.push(FINE_GRAINED_TOOL_STREAMING_BETA); - if (model3.reasoning && options?.thinkingEnabled === true && (options.interleavedThinking ?? true) && model3.compat?.forceAdaptiveThinking !== true) { + if (model2.reasoning && options?.thinkingEnabled === true && (options.interleavedThinking ?? true) && model2.compat?.forceAdaptiveThinking !== true) { features.push(INTERLEAVED_THINKING_BETA); } - if (shouldUseServerSideFallbackBeta(model3)) + if (shouldUseServerSideFallbackBeta(model2)) features.push(SERVER_SIDE_FALLBACK_BETA); - if (model3.compat?.supportsMidConvoEffort === true) { + if (model2.compat?.supportsMidConvoEffort === true) { features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA); } if (nativeToolChanges) features.push(INLINE_TOOLS_BETA); return [...new Set(features)]; } -function buildParams2(model3, context, isOAuthToken2, options, disablePreferredStrictTools = false) { - const { cacheControl } = getCacheControl(model3, options?.cacheRetention, options?.env); - const compat = getAnthropicCompat(model3); +function buildParams2(model2, context, isOAuthToken2, options, disablePreferredStrictTools = false) { + const { cacheControl } = getCacheControl(model2, options?.cacheRetention, options?.env); + const compat = getAnthropicCompat(model2); const initialSystemMessage = getInitialSystemMessage(context.messages); const initialSystemText = initialSystemMessage ? getSystemMessageText(initialSystemMessage) : ""; - const transformedMessages = transformMessages(context.messages, model3, normalizeToolCallId); + const transformedMessages = transformMessages(context.messages, model2, normalizeToolCallId); const conversationMessages = initialSystemMessage ? transformedMessages.slice(1) : transformedMessages; let hasPreferredStrictTools = false; const convertToolDefinitions = (tools, toolCacheControl2) => { @@ -40477,15 +40477,15 @@ function buildParams2(model3, context, isOAuthToken2, options, disablePreferredS }; const initialTools = initialSystemMessage?.toolsAdded ?? []; const nativeToolChanges = compat.supportsMidConvoSystemMessages && compat.supportsMidConvoToolChanges && initialTools.length > 0; - const thinkingDisabled = model3.reasoning && options?.thinkingEnabled === false && model3.thinkingLevelMap?.off !== null; - const effortMessages = model3.compat?.supportsMidConvoEffort === true && !thinkingDisabled; - const converted = convertMessages(conversationMessages, isOAuthToken2, cacheControl, compat.allowEmptySignature, effortMessages ? model3.provider : void 0, nativeToolChanges ? convertToolDefinitions : void 0); + const thinkingDisabled = model2.reasoning && options?.thinkingEnabled === false && model2.thinkingLevelMap?.off !== null; + const effortMessages = model2.compat?.supportsMidConvoEffort === true && !thinkingDisabled; + const converted = convertMessages(conversationMessages, isOAuthToken2, cacheControl, compat.allowEmptySignature, effortMessages ? model2.provider : void 0, nativeToolChanges ? convertToolDefinitions : void 0); const activeEffort = options?.effort ?? "high"; - const betaFeatures = getBetaFeatures(model3, context, isOAuthToken2, nativeToolChanges, options); + const betaFeatures = getBetaFeatures(model2, context, isOAuthToken2, nativeToolChanges, options); const params = { - model: model3.id, + model: model2.id, messages: effortMessages ? insertThinkingLevelMessages(converted, activeEffort) : converted.messages, - max_tokens: options?.maxTokens ?? model3.maxTokens, + max_tokens: options?.maxTokens ?? model2.maxTokens, stream: true, ...betaFeatures.length > 0 ? { betas: betaFeatures } : {} }; @@ -40513,7 +40513,7 @@ function buildParams2(model3, context, isOAuthToken2, options, disablePreferredS } ]; } - if (options?.temperature !== void 0 && !options?.thinkingEnabled && model3.compat?.supportsMidConvoEffort !== true && compat.supportsTemperature) { + if (options?.temperature !== void 0 && !options?.thinkingEnabled && model2.compat?.supportsMidConvoEffort !== true && compat.supportsTemperature) { params.temperature = options.temperature; } const toolCacheControl = compat.supportsCacheControlOnTools ? cacheControl : void 0; @@ -40534,9 +40534,9 @@ function buildParams2(model3, context, isOAuthToken2, options, disablePreferredS block_binding: { prefix_mismatch_behavior: "drop_block" } }; params.output_config = { effort: "low" }; - } else if (model3.reasoning && options?.thinkingEnabled) { + } else if (model2.reasoning && options?.thinkingEnabled) { const display = options.thinkingDisplay ?? "summarized"; - if (model3.compat?.forceAdaptiveThinking === true) { + if (model2.compat?.forceAdaptiveThinking === true) { params.thinking = { type: "adaptive", display }; if (options.effort) { params.output_config = { effort: options.effort }; @@ -40562,7 +40562,7 @@ function buildParams2(model3, context, isOAuthToken2, options, disablePreferredS params.tool_choice = options.toolChoice; } } - const allowedFallbackModels = model3.compat?.allowedFallbackModels; + const allowedFallbackModels = model2.compat?.allowedFallbackModels; if (allowedFallbackModels && allowedFallbackModels.length > 0) { params.fallbacks = allowedFallbackModels.map((fallback) => ({ model: fallback.model })); } @@ -40758,8 +40758,8 @@ function insertThinkingLevelMessages(converted, activeEffort) { messages.push({ role: "system", content: [], output_config: { effort: activeEffort } }); return messages; } -function shouldUseFineGrainedToolStreamingBeta(model3, context) { - return getCurrentTools(context.messages).length > 0 && !getAnthropicCompat(model3).supportsEagerToolInputStreaming; +function shouldUseFineGrainedToolStreamingBeta(model2, context) { + return getCurrentTools(context.messages).length > 0 && !getAnthropicCompat(model2).supportsEagerToolInputStreaming; } function convertTools(tools, isOAuthToken2, supportsEagerToolInputStreaming, supportsStrictTools, cacheControl, disablePreferredStrictTools = false) { if (!tools) @@ -40767,11 +40767,11 @@ function convertTools(tools, isOAuthToken2, supportsEagerToolInputStreaming, sup return tools.map((tool, index) => { const strict = disablePreferredStrictTools && prefersJsonSchemaStrictSampling(tool) ? void 0 : resolveJsonSchemaStrictSampling(tool, supportsStrictTools, isAnthropicStrictUnsupportedKeyword); const parameters = getJsonSchemaToolParameters(tool, strict); - const schema = parameters; + const schema4 = parameters; const legacyInputSchema = { type: "object", - properties: schema.properties ?? {}, - required: schema.required ?? [] + properties: schema4.properties ?? {}, + required: schema4.required ?? [] }; const inputSchema = strict === true ? { ...parameters, @@ -40889,17 +40889,17 @@ var init_anthropic_messages = __esm({ "content_block_delta", "content_block_stop" ]); - stream3 = (model3, context, options) => { + stream3 = (model2, context, options) => { const stream4 = new AssistantMessageEventStream(); - const normalizedContext = resolveTranscript(context, getAnthropicCompat(model3).supportsMidConvoSystemMessages); + const normalizedContext = resolveTranscript(context, getAnthropicCompat(model2).supportsMidConvoSystemMessages); const currentTools = getCurrentTools(normalizedContext.messages); (async () => { const output = { role: "assistant", content: [], - api: model3.api, - provider: model3.provider, - model: model3.id, + api: model2.api, + provider: model2.provider, + model: model2.id, usage: { input: 0, output: 0, @@ -40914,18 +40914,18 @@ var init_anthropic_messages = __esm({ try { let client; let isOAuth; - let usageModel = model3; + let usageModel = model2; let inputTransformations; if (options?.client) { client = options.client; isOAuth = false; } else { const apiKey = options?.apiKey; - const federation = getAnthropicFederation(model3, apiKey, options?.headers, options?.env); + const federation = getAnthropicFederation(model2, apiKey, options?.headers, options?.env); if (!federation) - assertRequestAuth(model3.provider, apiKey, options?.headers); + assertRequestAuth(model2.provider, apiKey, options?.headers); let copilotDynamicHeaders; - if (model3.provider === "github-copilot") { + if (model2.provider === "github-copilot") { const hasImages = hasCopilotVisionInput(normalizedContext.messages); copilotDynamicHeaders = buildCopilotDynamicHeaders({ messages: normalizedContext.messages, @@ -40934,7 +40934,7 @@ var init_anthropic_messages = __esm({ } const cacheRetention = resolveCacheRetention2(options?.cacheRetention, options?.env); const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId; - const created = createClient2(model3, apiKey, options?.headers, options?.fetch, copilotDynamicHeaders, cacheSessionId, federation, options?.identity); + const created = createClient2(model2, apiKey, options?.headers, options?.fetch, copilotDynamicHeaders, cacheSessionId, federation, options?.identity); client = created.client; isOAuth = created.isOAuthToken; } @@ -40947,11 +40947,11 @@ var init_anthropic_messages = __esm({ let response; for (; ; ) { options?.signal?.throwIfAborted(); - const built = buildParams2(model3, normalizedContext, isOAuth, options, disablePreferredStrictTools); + const built = buildParams2(model2, normalizedContext, isOAuth, options, disablePreferredStrictTools); if (built.providerThinkingLevel) output.providerThinkingLevel = built.providerThinkingLevel; let params = built.params; - const nextParams = await options?.onPayload?.(params, model3); + const nextParams = await options?.onPayload?.(params, model2); if (nextParams !== void 0) { params = { ...nextParams, stream: true }; } @@ -40975,7 +40975,7 @@ var init_anthropic_messages = __esm({ }); } } - await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model3); + await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model2); stream4.push({ type: "start", partial: output }); const openBlocks = /* @__PURE__ */ new Map(); const openBlock = (anthropicIndex) => { @@ -40983,17 +40983,17 @@ var init_anthropic_messages = __esm({ return open === void 0 ? void 0 : { ...open, block: output.content[open.contentIndex] }; }; for await (const event of iterateAnthropicEvents(response, options?.signal)) { - await options?.onProviderStreamEvent?.(event, model3); + await options?.onProviderStreamEvent?.(event, model2); if (event.type === "message_start") { output.responseId = event.message.id; const transformations = event.message.input_transformations; if (Array.isArray(transformations)) inputTransformations = transformations; const responseModel = event.message.model; - if (responseModel !== model3.id) + if (responseModel !== model2.id) output.responseModel = responseModel; - const fallbackCost = responseModel === model3.id ? void 0 : model3.compat?.allowedFallbackModels?.find((fallback) => fallback.provider === model3.provider && fallback.model === responseModel)?.cost; - usageModel = fallbackCost ? { ...model3, id: responseModel, cost: fallbackCost } : model3; + const fallbackCost = responseModel === model2.id ? void 0 : model2.compat?.allowedFallbackModels?.find((fallback) => fallback.provider === model2.provider && fallback.model === responseModel)?.cost; + usageModel = fallbackCost ? { ...model2, id: responseModel, cost: fallbackCost } : model2; output.usage.input = event.message.usage.input_tokens || 0; output.usage.output = event.message.usage.output_tokens || 0; output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0; @@ -41145,7 +41145,7 @@ var init_anthropic_messages = __esm({ } output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite; calculateCost(usageModel, output.usage); - if (isOpenRouterModel(model3) && event.usage) { + if (isOpenRouterModel(model2) && event.usage) { applyOpenRouterReportedCost(output.usage, event.usage); } } @@ -41183,31 +41183,31 @@ var init_anthropic_messages = __esm({ })(); return stream4; }; - streamSimple2 = (model3, context, options) => { - if (!getAnthropicFederation(model3, options?.apiKey, options?.headers, options?.env)) { - assertRequestAuth(model3.provider, options?.apiKey, options?.headers); + streamSimple2 = (model2, context, options) => { + if (!getAnthropicFederation(model2, options?.apiKey, options?.headers, options?.env)) { + assertRequestAuth(model2.provider, options?.apiKey, options?.headers); } const base = { - ...buildBaseOptions(model3, context, options, options?.apiKey), + ...buildBaseOptions(model2, context, options, options?.apiKey), toolChoice: options?.toolChoice }; if (!options?.reasoning) { - return stream3(model3, context, { + return stream3(model2, context, { ...base, thinkingEnabled: false }); } - if (model3.compat?.forceAdaptiveThinking === true) { - const effort = mapThinkingLevelToEffort(model3, options.reasoning); - return stream3(model3, context, { + if (model2.compat?.forceAdaptiveThinking === true) { + const effort = mapThinkingLevelToEffort(model2, options.reasoning); + return stream3(model2, context, { ...base, thinkingEnabled: true, effort }); } - const adjusted = adjustMaxTokensForThinking(base.maxTokens, model3.maxTokens, options.reasoning, options.thinkingBudgets); - const maxTokens = clampMaxTokensToContext(model3, context, adjusted.maxTokens); - return stream3(model3, context, { + const adjusted = adjustMaxTokensForThinking(base.maxTokens, model2.maxTokens, options.reasoning, options.thinkingBudgets); + const maxTokens = clampMaxTokensToContext(model2, context, adjusted.maxTokens); + return stream3(model2, context, { ...base, maxTokens, thinkingEnabled: true, @@ -41369,7 +41369,7 @@ init_models(); // node_modules/@earendil-works/pi-ai/dist/api/openai-decisions.lazy.js var openAIDecisionsApi = () => ({ - classify: async (model3, context, options) => (await Promise.resolve().then(() => (init_openai_decisions(), openai_decisions_exports))).classify(model3, context, options) + classify: async (model2, context, options) => (await Promise.resolve().then(() => (init_openai_decisions(), openai_decisions_exports))).classify(model2, context, options) }); // node_modules/@earendil-works/pi-ai/dist/api/openai-responses.lazy.js @@ -41450,7 +41450,7 @@ var openai_default = { "openai-decisions": { "classifier:gpt-6-luna": { type: "c // node_modules/@earendil-works/pi-ai/dist/model-catalog.js function flattenModelCatalog(groups, type) { - return Object.fromEntries(Object.values(groups).flatMap((models2) => Object.values(models2)).filter((model3) => model3.type === type).map((model3) => [model3.id, model3])); + return Object.fromEntries(Object.values(groups).flatMap((models2) => Object.values(models2)).filter((model2) => model2.type === type).map((model2) => [model2.id, model2])); } function flattenChatModelCatalog(_provider, groups) { return flattenModelCatalog(groups, "chat"); @@ -41487,7 +41487,7 @@ function openaiProvider() { ...Object.values(OPENAI_CLASSIFIER_MODELS) ], // Sign in with ChatGPT tokens only reach the Responses API; the Decisions API rejects them. - filterAllModels: (models2, credential) => credential?.type === "oauth" ? models2.filter((model3) => !isModelType(model3, "classifier")) : models2, + filterAllModels: (models2, credential) => credential?.type === "oauth" ? models2.filter((model2) => !isModelType(model2, "classifier")) : models2, api: openAIResponsesApi(), classifiers: { "openai-decisions": openAIDecisionsApi() @@ -41581,16 +41581,18 @@ function anthropicProvider() { } // proxy-models.ts -async function proxyModels(proxy2) { +async function proxyModels(proxy2, readProxy = async () => proxy2) { const models2 = createModels(); const base = proxy2.base_url.replace(/\/$/, ""); let catalog = []; try { - const response = await fetch(`${base}/v1/models`, { - headers: { Authorization: `Bearer ${proxy2.api_key}` }, - signal: AbortSignal.timeout(5e3) - }); - if (response.ok) catalog = (await response.json()).data ?? []; + if (proxy2.base_url && proxy2.api_key) { + const response = await fetch(`${base}/v1/models`, { + headers: { Authorization: `Bearer ${proxy2.api_key}` }, + signal: AbortSignal.timeout(5e3) + }); + if (response.ok) catalog = (await response.json()).data ?? []; + } } catch { } for (const [provider2, api2, path5, fallback] of [ @@ -41632,10 +41634,15 @@ async function proxyModels(proxy2) { ...provider2, baseUrl: entries2[0].baseUrl, getModels: () => entries2, - auth: { apiKey: { name: "Sausage proxy", resolve: async () => ({ - auth: { apiKey: proxy2.api_key, headers: { "Shopify-Usage-Tag": JSON.stringify(["pi", "sausage"]) } }, - source: "llm-proxy" - }) } } + auth: { apiKey: { name: "Sausage proxy", resolve: async () => { + const current = await readProxy(); + if (!current.base_url || !current.api_key) throw new Error("Set proxy.base_url and proxy.api_key in /etc/sausage/config.yaml before a model request"); + return { auth: { + apiKey: current.api_key, + baseUrl: current.base_url.replace(/\/$/, "") + entries2[0].baseUrl.slice(base.length), + headers: { "Shopify-Usage-Tag": JSON.stringify(["pi", "sausage"]) } + }, source: "/etc/sausage/config.yaml" }; + } } } }); } return models2; @@ -41774,11 +41781,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -41794,12 +41801,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -41840,12 +41847,12 @@ var Resolver = class { resources = /* @__PURE__ */ new Map(); anchors = /* @__PURE__ */ new Map(); indexed = false; - constructor(root2, options) { + constructor(root, options) { this.draft = options.draft === "7" ? "7" : "2020-12"; - this.root = root2; + this.root = root; this.options = options; this.rejectUnresolved = options.unresolvedRefs === "reject"; - this.rootBase = isSchemaObject(root2) ? this.baseFor(root2, DEFAULT_BASE) : DEFAULT_BASE; + this.rootBase = isSchemaObject(root) ? this.baseFor(root, DEFAULT_BASE) : DEFAULT_BASE; } /** * The base URI of `node`, whose parent has `base`: its `$id` changes it, unless draft 7 makes the `$id` inert. Once @@ -41867,8 +41874,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -41896,13 +41903,13 @@ var Resolver = class { const uri = resolveUri(ref, base); const doc = documentOf(uri); const fragment = uri.length > doc.length ? decodeURIComponent(uri.slice(doc.length + 1)) : ""; - const root2 = this.resources.has(doc) ? this.resources.get(doc) : this.load(doc); - if (root2 === void 0) + const root = this.resources.has(doc) ? this.resources.get(doc) : this.load(doc); + if (root === void 0) throw new Error(`Unresolved $ref ${ref} (no schema registered for ${doc})`); if (fragment === "") - return { node: root2, base: doc }; + return { node: root, base: doc }; if (fragment.startsWith("/")) - return this.pointer(root2, doc, fragment); + return this.pointer(root, doc, fragment); const target = this.anchors.get(`${doc}#${fragment}`); if (target === void 0) throw new Error(`Unresolved $ref ${ref} (no anchor ${fragment} in ${doc})`); @@ -41944,10 +41951,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -41957,15 +41964,15 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } - pointer(root2, base, fragment) { - let node = root2; + pointer(root, base, fragment) { + let node = root; let b = base; for (const raw of fragment.split("/").slice(1)) { const key = raw.replace(/~1/g, "/").replace(/~0/g, "~"); @@ -42049,9 +42056,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -42113,26 +42120,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -42147,7 +42154,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -42156,10 +42163,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -42265,8 +42272,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -42279,7 +42286,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -42289,11 +42296,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -42307,19 +42314,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -42331,9 +42338,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -42347,12 +42354,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -42360,7 +42367,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -42368,31 +42375,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -42488,11 +42495,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -42885,9 +42892,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -43146,9 +43153,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -43214,9 +43221,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -43227,7 +43234,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -43636,9 +43643,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -43990,9 +43997,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -44001,9 +44008,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -44035,18 +44042,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -44104,7 +44111,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -44127,34 +44134,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -44173,12 +44180,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -44187,22 +44194,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -44210,42 +44217,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -44253,7 +44260,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -44262,16 +44269,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -44284,28 +44291,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -44331,7 +44338,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -44359,7 +44366,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -44567,8 +44574,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -45216,16 +45223,16 @@ var DATA_DESCRIPTOR2 = { configurable: true }; function applyImmutableTrusted(target, operations) { - let root2 = target; + let root = target; const owned = /* @__PURE__ */ new WeakSet(); for (const operation of operations) { if (operation[0] === "r") { - root2 = operation[1]; + root = operation[1]; continue; } if (operation[0] === "p" || operation[0] === "m") { - const copied2 = copyPath(root2, operation[1], operation[1].length, owned); - root2 = copied2.root; + const copied2 = copyPath(root, operation[1], operation[1].length, owned); + root = copied2.root; if (!Array.isArray(copied2.target)) throw new TypeError("Trusted array operation target is not an array"); if (operation[0] === "p") @@ -45235,8 +45242,8 @@ function applyImmutableTrusted(target, operations) { continue; } const path5 = operation[1]; - const copied = copyPath(root2, path5, path5.length - 1, owned); - root2 = copied.root; + const copied = copyPath(root, path5, path5.length - 1, owned); + root = copied.root; const key = path5[path5.length - 1]; switch (operation[0]) { case "s": @@ -45266,14 +45273,14 @@ function applyImmutableTrusted(target, operations) { } } } - return root2; + return root; } -function copyPath(root2, path5, length, owned) { - if (!isContainer2(root2)) +function copyPath(root, path5, length, owned) { + if (!isContainer2(root)) throw new TypeError("Trusted operation root is not a container"); - let copiedRoot = root2; - if (!owned.has(root2)) { - copiedRoot = shallowCopy(root2); + let copiedRoot = root; + if (!owned.has(root)) { + copiedRoot = shallowCopy(root); owned.add(copiedRoot); } let destination = copiedRoot; @@ -45571,7 +45578,7 @@ function materializeOperations(base, operations) { } return applyImmutableTrusted(base, operations); } -function createContext(tracker, owner, baseRevision, root2, replacement, base) { +function createContext(tracker, owner, baseRevision, root, replacement, base) { const context = { owner, tracker, @@ -45591,7 +45598,7 @@ function createContext(tracker, owner, baseRevision, root2, replacement, base) { simpleObjectMaterialization: false, registryRef: void 0 }; - context.root = createNode(context, root2, void 0); + context.root = createNode(context, root, void 0); return context; } var sharedObjectHandler = { @@ -46033,45 +46040,45 @@ function mergePieceTrees(left, right) { updatePieceNode(right); return right; } -function splitPieceTree(overlay, root2, index) { - if (root2 === void 0) +function splitPieceTree(overlay, root, index) { + if (root === void 0) return [void 0, void 0]; - const leftLength = treeElements(root2.left); + const leftLength = treeElements(root.left); if (index < leftLength) { - const [left, right] = splitPieceTree(overlay, root2.left, index); - root2.left = right; - updatePieceNode(root2); - return [left, root2]; + const [left, right] = splitPieceTree(overlay, root.left, index); + root.left = right; + updatePieceNode(root); + return [left, root]; } - const pieceEnd = leftLength + root2.piece.length; + const pieceEnd = leftLength + root.piece.length; if (index > pieceEnd) { - const [left, right] = splitPieceTree(overlay, root2.right, index - pieceEnd); - root2.right = left; - updatePieceNode(root2); - return [root2, right]; + const [left, right] = splitPieceTree(overlay, root.right, index - pieceEnd); + root.right = left; + updatePieceNode(root); + return [root, right]; } if (index === leftLength) { - const left = root2.left; - root2.left = void 0; - updatePieceNode(root2); - return [left, root2]; + const left = root.left; + root.left = void 0; + updatePieceNode(root); + return [left, root]; } if (index === pieceEnd) { - const right = root2.right; - root2.right = void 0; - updatePieceNode(root2); - return [root2, right]; + const right = root.right; + root.right = void 0; + updatePieceNode(root); + return [root, right]; } const offset = index - leftLength; - const first = { ...root2.piece, length: offset }; + const first = { ...root.piece, length: offset }; const second = { - ...root2.piece, - start: root2.piece.start + root2.piece.step * offset, - length: root2.piece.length - offset + ...root.piece, + start: root.piece.start + root.piece.step * offset, + length: root.piece.length - offset }; return [ - mergePieceTrees(root2.left, createPieceNode(overlay, first)), - mergePieceTrees(createPieceNode(overlay, second), root2.right) + mergePieceTrees(root.left, createPieceNode(overlay, first)), + mergePieceTrees(createPieceNode(overlay, second), root.right) ]; } function leftmostPieceNode(node) { @@ -46130,10 +46137,10 @@ function piecesOf(overlay) { } function treeFromPieces(overlay, pieces) { mergePieces(pieces); - let root2; + let root; for (const piece of pieces) - root2 = mergePieceTrees(root2, createPieceNode(overlay, piece)); - return root2; + root = mergePieceTrees(root, createPieceNode(overlay, piece)); + return root; } function replaceAllPieces(overlay, pieces) { overlay.root = treeFromPieces(overlay, pieces); @@ -47713,17 +47720,17 @@ function apply(target, ops3) { return applyOps(target, ops3); } function applyOps(target, ops3) { - let root2 = target; + let root = target; for (const op2 of ops3) { assertValidOp(op2); if (op2[0] === "r") { - root2 = op2[1]; + root = op2[1]; continue; } const path5 = op2[1]; assertSafePath(path5); if (op2[0] === "p") { - const target_ = path5.length === 0 ? root2 : resolve(root2, path5); + const target_ = path5.length === 0 ? root : resolve(root, path5); if (!Array.isArray(target_)) throw new PathError(path5); target_.splice(op2[2], op2[3]); @@ -47734,7 +47741,7 @@ function applyOps(target, ops3) { continue; } if (op2[0] === "m") { - const target_ = path5.length === 0 ? root2 : resolve(root2, path5); + const target_ = path5.length === 0 ? root : resolve(root, path5); if (!Array.isArray(target_) || target_.length !== op2[2].length) throw new PathError(path5); const previous = target_.slice(); @@ -47742,7 +47749,7 @@ function applyOps(target, ops3) { target_[index] = previous[op2[2][index]]; continue; } - const parent = resolve(root2, path5.slice(0, -1)); + const parent = resolve(root, path5.slice(0, -1)); const key = path5[path5.length - 1]; if (Array.isArray(parent)) { if (typeof key !== "number") @@ -47781,39 +47788,39 @@ function applyOps(target, ops3) { } } } - return root2; + return root; } function applyImmutable(target, ops3) { return applyImmutableBatches(target, [ops3]); } function applyImmutableBatches(target, batches) { - let root2 = target; + let root = target; const owned = /* @__PURE__ */ new WeakSet(); for (const ops3 of batches) { for (const op2 of ops3) { assertValidOp(op2); if (op2[0] === "r") { - root2 = op2[1]; + root = op2[1]; continue; } if (op2[0] === "p") { - const appended = appendCopy(root2, op2, owned); + const appended = appendCopy(root, op2, owned); if (appended !== void 0) { - root2 = appended; + root = appended; continue; } } - root2 = copyContainers(root2, op2[0] === "p" || op2[0] === "m" ? op2[1] : op2[1].slice(0, -1), owned); - root2 = applyOps(root2, [op2]); + root = copyContainers(root, op2[0] === "p" || op2[0] === "m" ? op2[1] : op2[1].slice(0, -1), owned); + root = applyOps(root, [op2]); } } - return root2; + return root; } -function appendCopy(root2, op2, owned) { +function appendCopy(root, op2, owned) { const [, path5, index, deleteCount, items] = op2; if (deleteCount !== 0) return void 0; - let target = root2; + let target = root; for (const segment of path5) { const valid = typeof segment === "string" ? !RESERVED_SEGMENTS.has(segment) && isObj3(target) && !Array.isArray(target) : Number.isInteger(segment) && segment >= 0 && Array.isArray(target); if (!valid || !Object.hasOwn(target, segment)) @@ -47827,7 +47834,7 @@ function appendCopy(root2, op2, owned) { if (path5.length === 0) return appended; const parentPath = path5.slice(0, -1); - const copiedRoot = copyContainers(root2, parentPath, owned); + const copiedRoot = copyContainers(root, parentPath, owned); Object.defineProperty(resolve(copiedRoot, parentPath), path5[path5.length - 1], { value: appended, writable: true, @@ -47836,7 +47843,7 @@ function appendCopy(root2, op2, owned) { }); return copiedRoot; } -function copyContainers(root2, path5, owned) { +function copyContainers(root, path5, owned) { const copy2 = (value2) => { if (Array.isArray(value2)) return value2.slice(); @@ -47844,13 +47851,13 @@ function copyContainers(root2, path5, owned) { throw new PathError(path5); return Object.getPrototypeOf(value2) === null ? Object.assign(/* @__PURE__ */ Object.create(null), value2) : { ...value2 }; }; - if (!isObj3(root2)) + if (!isObj3(root)) throw new PathError(path5); let copiedRoot; - if (owned.has(root2)) - copiedRoot = root2; + if (owned.has(root)) + copiedRoot = root; else { - copiedRoot = copy2(root2); + copiedRoot = copy2(root); owned.add(copiedRoot); } let destination = copiedRoot; @@ -47878,8 +47885,8 @@ function copyContainers(root2, path5, owned) { } return copiedRoot; } -function resolveValue(root2, path5) { - let node = root2; +function resolveValue(root, path5) { + let node = root; for (const seg of path5) { if (!isObj3(node)) throw new PathError(path5); @@ -47891,8 +47898,8 @@ function resolveValue(root2, path5) { } return node; } -function resolve(root2, path5) { - const node = resolveValue(root2, path5); +function resolve(root, path5) { + const node = resolveValue(root, path5); if (!isObj3(node)) throw new PathError(path5); return node; @@ -48148,10 +48155,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -48192,11 +48199,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -48260,8 +48267,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -48302,15 +48309,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -48814,8 +48821,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -49024,7 +49031,7 @@ var RefImpl = class { } catch (error) { return Promise.reject(error); } - return this.object.host.root((root2) => this.object.call(this, name, args, root2), { + return this.object.host.root((root) => this.object.call(this, name, args, root), { signal: ctx?.signal }); } @@ -49286,15 +49293,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -49478,9 +49485,9 @@ var ObjectImpl = class { const decl = this.decls.listeners.get(key); if (decl === void 0 || this.status !== "live" && this.status !== "activating") return; - const invocation = this.host.root((root2) => { - this.lease(root2); - const child = root2.child(this); + const invocation = this.host.root((root) => { + this.lease(root); + const child = root.child(this); return this.#invoke(async () => { try { await decl.fn(event, child); @@ -49555,8 +49562,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -49667,16 +49674,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -49693,18 +49700,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -49749,13 +49756,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -49764,7 +49771,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -49772,7 +49779,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -49874,15 +49881,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -50248,17 +50255,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -50430,11 +50437,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -51636,7 +51643,7 @@ var Connection = class { if (this.remotes.has(hold)) this.send({ t: wanted ? "sub" : "unsub", hold }); } - call(hold, member, args, root2, signal) { + call(hold, member, args, root, signal) { const id = this.nextId(); return new Promise((resolve2, reject2) => { if (signal.aborted) { @@ -51660,10 +51667,10 @@ var Connection = class { reject2(error); } }); - const carried = root2 !== void 0 && this.host.kind === "host"; + const carried = root !== void 0 && this.host.kind === "host"; if (carried) - this.host.rootSent(root2.rootId, this); - this.send({ t: "call", id, hold, member, args, ...carried ? { root: root2 } : {} }); + this.host.rootSent(root.rootId, this); + this.send({ t: "call", id, hold, member, args, ...carried ? { root } : {} }); }); } // ─── receiving ─── @@ -52060,7 +52067,7 @@ var Connection = class { } const controller = new AbortController(); this.incoming.set(frame.id, controller); - const root2 = this.peer.kind === "host" ? this.#admitRoot(frame.root) : void 0; + const root = this.peer.kind === "host" ? this.#admitRoot(frame.root) : void 0; const principal = served.kind === "local" ? served.principal : served.relay.principal; const options = { principal, signal: controller.signal }; const run2 = served.kind === "local" ? (ctx) => served.ref.object.call(served.ref, frame.member, unpack(frame.args), ctx) : (ctx) => relayCall( @@ -52071,7 +52078,7 @@ var Connection = class { ctx.signal, this.host ); - const result = root2 === void 0 ? this.host.root(run2, options) : this.host.joinRoot(root2.rootId, root2.codeVersion, run2, { ...options, from: this }); + const result = root === void 0 ? this.host.root(run2, options) : this.host.joinRoot(root.rootId, root.codeVersion, run2, { ...options, from: this }); result.then((value2) => this.send({ t: "result", id: frame.id, value: value2 }), (error) => this.send({ t: "result", id: frame.id, error: toWireError(error) })).finally(() => this.incoming.delete(frame.id)); } /** @@ -52080,17 +52087,17 @@ var Connection = class { * and keeps that code version for its later calls (`superseded` once this host retired it). Other unknown code * versions stay `superseded`. */ - #admitRoot(root2) { - if (root2 === void 0 || this.role !== "downstream" || !this.fencedCodeVersions.has(root2.codeVersion)) - return root2; - if (this.host.hasCodeVersion(root2.codeVersion)) - return root2; - let codeVersion = this.#admitted.get(root2.rootId); + #admitRoot(root) { + if (root === void 0 || this.role !== "downstream" || !this.fencedCodeVersions.has(root.codeVersion)) + return root; + if (this.host.hasCodeVersion(root.codeVersion)) + return root; + let codeVersion = this.#admitted.get(root.rootId); if (codeVersion === void 0) { codeVersion = this.host.current.id; - this.#admitted.set(root2.rootId, codeVersion); + this.#admitted.set(root.rootId, codeVersion); } - return { rootId: root2.rootId, codeVersion }; + return { rootId: root.rootId, codeVersion }; } #onHoldReply(frame) { const relay = this.relayedRefs.get(frame.id); @@ -52197,7 +52204,7 @@ var Connection = class { }; var stateKey = (hold, m) => `s${hold}\0${m}`; var unitKey = (hold) => `u${hold}`; -async function relayCall(relay, frame, root2, signal, host) { +async function relayCall(relay, frame, root, signal, host) { const abortError2 = () => new ChordError("aborted", "call cancelled", { cause: signal.reason }); if (signal.aborted) throw abortError2(); @@ -52219,8 +52226,8 @@ async function relayCall(relay, frame, root2, signal, host) { const call = new RelayCall(relay, frame.id, down.nextId(), { resolve: resolve2, reject: reject2 }); onCancel = () => call.cancel(abortError2(), true); signal.addEventListener("abort", onCancel, { once: true }); - host.rootSent(root2.rootId, down); - down.send({ t: "call", id: call.downId, hold: relay.downId, member: frame.member, args: frame.args, root: root2 }); + host.rootSent(root.rootId, down); + down.send({ t: "call", id: call.downId, hold: relay.downId, member: frame.member, args: frame.args, root }); }); } finally { signal.removeEventListener("abort", onAbort); @@ -52331,10 +52338,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -52361,12 +52368,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -52645,8 +52652,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -52808,7 +52815,7 @@ var RemoteRef = class { return Promise.reject(error); } if (ctx === void 0 || ctx.holder) { - return host.root((root2) => this.#call(name, args, root2), { signal: ctx?.signal }); + return host.root((root) => this.#call(name, args, root), { signal: ctx?.signal }); } return this.#call(name, args, ctx); }; @@ -53075,11 +53082,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -53327,15 +53334,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry3.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry3.name, set); + let set2 = this.#subscribers.get(registry3.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry3.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -54930,19 +54937,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -55701,14 +55708,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -56156,8 +56163,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -56190,8 +56197,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -56209,7 +56216,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -57074,7 +57081,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -57084,15 +57091,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -57103,7 +57110,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -57116,7 +57123,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -57185,7 +57192,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -57193,7 +57200,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -57248,7 +57255,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -57276,9 +57283,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -57909,7 +57916,7 @@ async function addTools(tx, conversationId, added) { state2.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state2, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -57917,27 +57924,27 @@ function applyChange(state2, change) { else state2[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions2 = change.extensions; - set("extensions", extensions2 === void 0 || extensions2 === null ? extensions2 : isList(extensions2) ? names(extensions2) : { + set2("extensions", extensions2 === void 0 || extensions2 === null ? extensions2 : isList(extensions2) ? names(extensions2) : { ...extensions2.add === void 0 ? {} : { add: names(extensions2.add) }, ...extensions2.remove === void 0 ? {} : { remove: names(extensions2.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -57945,13 +57952,13 @@ function isList(value2) { function names(items) { return items.map((item) => item.name); } -async function createAgent(tx, conversation) { - if (conversation.parent !== void 0) +async function createAgent(tx, conversation2) { + if (conversation2.parent !== void 0) return; - const agent = await tx.doc(AgentDoc, conversation.id); - if (conversation.owner === void 0) + const agent = await tx.doc(AgentDoc, conversation2.id); + if (conversation2.owner === void 0) return; - const owner = await tx.doc(AgentDoc, conversation.owner.conversationId); + const owner = await tx.doc(AgentDoc, conversation2.owner.conversationId); Object.assign(agent, copyJson(owner)); } function agentHooks(agent, taskName) { @@ -58492,7 +58499,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -58500,7 +58507,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -58865,9 +58872,9 @@ var PartialChanges = class { function applyChange2(block, change) { const key = change.path.at(-1); if (key === void 0) { - const root2 = change.kind === "set" ? value(change) : void 0; - if (isRecord3(root2)) - block.arguments = root2; + const root = change.kind === "set" ? value(change) : void 0; + if (isRecord3(root)) + block.arguments = root; return; } let parent = block.arguments; @@ -58928,21 +58935,21 @@ ${text2} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -58984,14 +58991,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -59018,9 +59025,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -59203,12 +59210,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -59222,16 +59229,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -59709,8 +59716,8 @@ var TaskScheduler = class { if (await this.#chainKeys(parentNode(record2), overlay, keys, reached) !== void 0) keys.add(ROOTS_KEY); } - for (const conversation of conversations) { - const owner = conversation.owner?.taskId; + for (const conversation2 of conversations) { + const owner = conversation2.owner?.taskId; if (owner === void 0) continue; await this.#loadChain({ task: owner }, overlay); @@ -59726,21 +59733,21 @@ var TaskScheduler = class { */ async #chainKeys(start, overlay, keys, reached) { const walked = []; - let root2; + let root; let node = start; while (node !== void 0 && node !== null) { const key = ownedKey(node); if (reached.has(key)) { - root2 = reached.get(key); + root = reached.get(key); break; } keys.add(key); walked.push(key); if (typeof node === "string") { - const conversation = conversationOf(node); - node = this.#edge(conversation, overlay); + const conversation2 = conversationOf(node); + node = this.#edge(conversation2, overlay); if (node === null) - root2 = conversation; + root = conversation2; continue; } let record2 = overlay.tasks.get(node); @@ -59758,8 +59765,8 @@ var TaskScheduler = class { node = above === void 0 ? void 0 : parentNode(above); } for (const key of walked) - reached.set(key, root2); - return root2; + reached.set(key, root); + return root; } // ─── Scheduling ──────────────────────────────────────────────────────── #observe(publication) { @@ -59829,8 +59836,8 @@ var TaskScheduler = class { continue; if (this.#intent.size === 0) continue; - const conversation = change.value.conversationId; - if (!this.#known(conversationNode(conversation)) || this.#belowCancelled({ conversation })) { + const conversation2 = change.value.conversationId; + if (!this.#known(conversationNode(conversation2)) || this.#belowCancelled({ conversation: conversation2 })) { this.#cascadePending = true; } } @@ -60482,11 +60489,11 @@ var TaskScheduler = class { if (parent === void 0) return; if (parent === null) { - const root2 = conversationOf(node); + const root = conversationOf(node); if (needed) - this.#roots.add(root2); + this.#roots.add(root); else - this.#roots.delete(root2); + this.#roots.delete(root); return; } if (this.#below.get(parent)?.has(node) === true === needed) @@ -61816,20 +61823,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -62737,13 +62744,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -63345,18 +63352,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -63536,7 +63543,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -63550,7 +63557,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -63619,10 +63626,10 @@ var GenerationTask = defineTask({ const { conversationId } = runtime; const agent = await runtime.agent(context); const settings = runtime.settings; - const { model: model3, thinkingLevel } = agent; - const resolved = model3 === void 0 ? void 0 : runtime.models.getModel(model3.provider, model3.modelId); - if (model3 === void 0 || resolved === void 0) - return failNoModel(runtime, model3, context); + const { model: model2, thinkingLevel } = agent; + const resolved = model2 === void 0 ? void 0 : runtime.models.getModel(model2.provider, model2.modelId); + if (model2 === void 0 || resolved === void 0) + return failNoModel(runtime, model2, context); const { attempt, compacted, overflow, threshold: blocked } = task.state.checkpoint; if (compacted !== void 0 && overflow !== void 0) { const [outcome] = await runtime.outcomes([compacted], context); @@ -63655,7 +63662,7 @@ var GenerationTask = defineTask({ ...optionalExtension(sectionExtension(agent, section2.key)) }), context); const entries2 = planSystemEntries(view2, desired, agent.tools, runtime.now()); - const threshold = compacted === void 0 ? thresholdCompaction(view2, entries2, resolved.contextWindow, compactionPolicy(settings, model3)) : void 0; + const threshold = compacted === void 0 ? thresholdCompaction(view2, entries2, resolved.contextWindow, compactionPolicy(settings, model2)) : void 0; if (threshold === "blocking") { await runtime.commit(async (tx) => { const child = await createCompaction(tx, conversationId, { reason: "threshold" }, runtime.taskId); @@ -63674,7 +63681,7 @@ var GenerationTask = defineTask({ const request2 = { attempt, ...compacted === void 0 ? {} : { compacted }, - model: model3, + model: model2, thinkingLevel, streamOptions: settings.stream, cutoff @@ -63695,8 +63702,8 @@ var GenerationTask = defineTask({ live.generation = { attempt }; return void 0; }, context, PROGRESS_COMMIT); - const model3 = runtime.models.getModel(ref.provider, ref.modelId); - if (model3 === void 0) + const model2 = runtime.models.getModel(ref.provider, ref.modelId); + if (model2 === void 0) return failNoModel(runtime, ref, context); const view2 = await runtime.context(conversationId, context, { at: cutoff }); let messages = view2.messages; @@ -63711,9 +63718,9 @@ var GenerationTask = defineTask({ telemetry: context.telemetry, sessionId: await ensureProviderSessionId(runtime, context), ...thinkingLevel === "off" ? {} : { reasoning: thinkingLevel }, - onPayload: (payload) => providerPayload(runtime, model3, payload, context) + onPayload: (payload) => providerPayload(runtime, model2, payload, context) }; - const message = await streamResponse(runtime, model3, messages, options, attempt, context); + const message = await streamResponse(runtime, model2, messages, options, attempt, context); const request2 = { attempt, compacted, model: ref, thinkingLevel, cutoff, messages: view2.messages }; await classify2(runtime, request2, message, context); }, @@ -63748,10 +63755,10 @@ var GenerationTask = defineTask({ return interrupted(runtime, task.state.checkpoint, context); if (pollAt > runtime.now()) return runtime.sleepUntil(pollAt, task.state.checkpoint, context); - const model3 = runtime.models.getModel(ref.provider, ref.modelId); - if (model3 === void 0) + const model2 = runtime.models.getModel(ref.provider, ref.modelId); + if (model2 === void 0) return failNoModel(runtime, ref, context); - const message = await runtime.models.fetchDeferred(model3, handle, { + const message = await runtime.models.fetchDeferred(model2, handle, { signal: runtime.signal, telemetry: context.telemetry }); @@ -63935,11 +63942,11 @@ function deferredOf(checkpoint) { return checkpoint.phase === "retry" ? checkpoint.poll : void 0; } async function cancelDeferred(runtime, checkpoint, context) { - const model3 = runtime.models.getModel(checkpoint.model.provider, checkpoint.model.modelId); - if (model3 === void 0) + const model2 = runtime.models.getModel(checkpoint.model.provider, checkpoint.model.modelId); + if (model2 === void 0) return; try { - await runtime.models.cancelDeferred(model3, checkpoint.handle, { + await runtime.models.cancelDeferred(model2, checkpoint.handle, { signal: runtime.signal, telemetry: context.telemetry }); @@ -63996,16 +64003,16 @@ async function convertPartial(tx, live, conversationId) { const message = copyJson(partial2); await appendAssistant(tx, conversationId, { ...message, stopReason: "aborted" }); } -async function providerPayload(runtime, model3, payload, context) { +async function providerPayload(runtime, model2, payload, context) { let current = payload; await runtime.hooks.each("beforeProviderRequest", async (hook2) => { - const replaced = await hook2({ model: model3, payload: current }, runtime, context); + const replaced = await hook2({ model: model2, payload: current }, runtime, context); if (replaced !== void 0) current = replaced.payload; }); return current; } -async function streamResponse(runtime, model3, messages, options, attempt, context) { +async function streamResponse(runtime, model2, messages, options, attempt, context) { const interval = runtime.settings.progress.partialIntervalMs; let pending; let timer; @@ -64042,7 +64049,7 @@ async function streamResponse(runtime, model3, messages, options, attempt, conte }); }; try { - const events = runtime.models.streamSimple(model3, { messages: [...messages] }, options); + const events = runtime.models.streamSimple(model2, { messages: [...messages] }, options); for await (const event of events) { if (event.type === "done" || event.type === "error" || event.partial.content.length === 0) continue; @@ -64811,8 +64818,8 @@ var CompactionTask = defineTask({ const agent = await runtime.agent(context); const settings = runtime.settings; const ref = agent.model; - const model3 = ref === void 0 ? void 0 : runtime.models.getModel(ref.provider, ref.modelId); - if (ref === void 0 || model3 === void 0) + const model2 = ref === void 0 ? void 0 : runtime.models.getModel(ref.provider, ref.modelId); + if (ref === void 0 || model2 === void 0) return failNoModel2(runtime, ref, context); const policy = compactionPolicy(settings, ref); const view2 = await runtime.context(conversationId, context); @@ -64842,7 +64849,7 @@ var CompactionTask = defineTask({ model: ref, thinkingLevel: agent.thinkingLevel, streamOptions: settings.stream, - maxTokens: Math.min(Math.floor(0.8 * policy.reserveTokens), model3.maxTokens > 0 ? model3.maxTokens : Number.POSITIVE_INFINITY), + maxTokens: Math.min(Math.floor(0.8 * policy.reserveTokens), model2.maxTokens > 0 ? model2.maxTokens : Number.POSITIVE_INFINITY), tail: view2.entries.reduce((tail, entry2) => entry2.id > tail ? entry2.id : tail, firstKept), firstKept }; @@ -64853,8 +64860,8 @@ var CompactionTask = defineTask({ return failCutOff(runtime, task, context); const { phase: _, ...request2 } = task.state.checkpoint; const { model: ref, thinkingLevel, streamOptions, maxTokens, tail, firstKept, attempt } = request2; - const model3 = runtime.models.getModel(ref.provider, ref.modelId); - if (model3 === void 0) + const model2 = runtime.models.getModel(ref.provider, ref.modelId); + if (model2 === void 0) return failNoModel2(runtime, ref, context); const view2 = await runtime.context(runtime.conversationId, context, { at: tail }); const cut = view2.entries.findIndex((entry2) => entry2.id === firstKept); @@ -64877,7 +64884,7 @@ var CompactionTask = defineTask({ sessionId: await ensureProviderSessionId(runtime, context), ...thinkingLevel === "off" ? {} : { reasoning: thinkingLevel } }; - const message = await runtime.models.completeSimple(model3, { messages }, options); + const message = await runtime.models.completeSimple(model2, { messages }, options); runtime.signal.throwIfAborted(); const summary = summaryText(message); const policy = runtime.settings.retry; @@ -64936,9 +64943,9 @@ async function createCompaction(tx, conversationId, input, owner) { addCompactionStatus(await tx.doc(LiveDoc, conversationId), status); return taskId; } -function compactionPolicy(settings, model3) { +function compactionPolicy(settings, model2) { const { modelOverrides, ...policy } = settings.compaction; - const override = modelOverrides?.[`${model3.provider}/${model3.modelId}`]; + const override = modelOverrides?.[`${model2.provider}/${model2.modelId}`]; return { enabled: override?.enabled ?? policy.enabled, reserveTokens: override?.reserveTokens ?? policy.reserveTokens, @@ -65347,7 +65354,7 @@ var TaskGraphView = class { records.sort((a, b) => a.id - b.id); for (const record2 of records) { const owned = await scanAll((cursor) => storage2.scanConversations({ ownerTaskId: record2.id }, SCAN_PAGE_SIZE4, cursor, context)); - const conversations = owned.map((conversation) => conversation.id).sort((a, b) => a - b); + const conversations = owned.map((conversation2) => conversation2.id).sort((a, b) => a - b); const subject = blockedSubject(record2); tasks[String(record2.id)] = nodeOf2(record2, conversations, this.#blocking.blocked(subject)); live.set(String(record2.id), subject); @@ -65546,8 +65553,8 @@ var ConversationViews = class { } /** Hydrate a mount on the line, through the line's `storage`. */ async #build(storage2, id, context) { - const conversation = await storage2.conversation(id, context); - if (conversation === void 0) + const conversation2 = await storage2.conversation(id, context); + if (conversation2 === void 0) throw new Error(`Conversation ${id} does not exist`); const docs = {}; const incarnations = /* @__PURE__ */ new Map(); @@ -65558,11 +65565,11 @@ var ConversationViews = class { docs[token.definition.kind] = loaded.value; incarnations.set(token.definition.kind, { id: loaded.record.id, version: loaded.version }); } - return { conversation, docs, incarnations, observers: /* @__PURE__ */ new Set() }; + return { conversation: conversation2, docs, incarnations, observers: /* @__PURE__ */ new Set() }; } }; -function view(conversation, entries2, before, docs) { - return before === void 0 ? { conversation, entries: entries2, docs } : { conversation, entries: entries2, before, docs }; +function view(conversation2, entries2, before, docs) { + return before === void 0 ? { conversation: conversation2, entries: entries2, docs } : { conversation: conversation2, entries: entries2, before, docs }; } async function loadWindow(storage2, conversationId, bounds, context) { const { from, min, max } = bounds; @@ -65690,8 +65697,8 @@ var ConversationImpl = class { return this.#host.harness.commitWith((tx) => createCompaction(tx, this.id, input), context); } async reset(handoff, context) { - const model3 = handoff === void 0 ? {} : { model: [{ role: "user", content: handoff, timestamp: this.#host.now() }] }; - const entry2 = { kind: ResetEntry.kind, head: "self", ...model3 }; + const model2 = handoff === void 0 ? {} : { model: [{ role: "user", content: handoff, timestamp: this.#host.now() }] }; + const entry2 = { kind: ResetEntry.kind, head: "self", ...model2 }; await this.#host.submissions.submit(this.id, { type: "write", entry: entry2 }, context); } commit(change, context, options) { @@ -66492,16 +66499,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -66509,14 +66516,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -66554,7 +66561,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -66572,7 +66579,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -66642,9 +66649,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -66705,11 +66712,11 @@ var MemoryStorage = class { const entry2 = this.state.entries.get(ids[index]); return clone({ ...entry2, head: entry2.head }); } - const conversation = this.state.conversations.get(currentId); - if (conversation.parent === void 0) + const conversation2 = this.state.conversations.get(currentId); + if (conversation2.parent === void 0) return void 0; - upperEntryId = Math.min(upperEntryId, conversation.parent.at); - currentId = conversation.parent.conversationId; + upperEntryId = Math.min(upperEntryId, conversation2.parent.at); + currentId = conversation2.parent.conversationId; } } async scanEntries(query, limit3, cursor, _context) { @@ -66857,13 +66864,13 @@ var MemoryStorage = class { break; yield this.state.entries.get(id); } - const conversation = this.state.conversations.get(currentId); - if (conversation.parent === void 0) + const conversation2 = this.state.conversations.get(currentId); + if (conversation2.parent === void 0) break; - upperEntryId = Math.min(upperEntryId, conversation.parent.at); + upperEntryId = Math.min(upperEntryId, conversation2.parent.at); if (upperEntryId < minEntryId) break; - currentId = conversation.parent.conversationId; + currentId = conversation2.parent.conversationId; } } /** Visible entries oldest first: the fork chain's segments from the root conversation forward. */ @@ -66876,13 +66883,13 @@ var MemoryStorage = class { let upperEntryId = maxEntryId; while (true) { segments.push({ conversationId: currentId, upper: upperEntryId }); - const conversation = this.state.conversations.get(currentId); - if (conversation.parent === void 0) + const conversation2 = this.state.conversations.get(currentId); + if (conversation2.parent === void 0) break; - upperEntryId = Math.min(upperEntryId, conversation.parent.at); + upperEntryId = Math.min(upperEntryId, conversation2.parent.at); if (upperEntryId < minEntryId) break; - currentId = conversation.parent.conversationId; + currentId = conversation2.parent.conversationId; } for (const segment of segments.reverse()) { const ids = this.state.entryIds.get(segment.conversationId) ?? []; @@ -66987,16 +66994,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -67014,14 +67021,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -68527,10 +68534,10 @@ async function readImage(reader, info, path5, mimeType, processor, { vision, lim } async function imageModel(api2, context) { const ref = (await api2.agent(context)).model; - const model3 = ref === void 0 ? void 0 : api2.models.getModel(ref.provider, ref.modelId); - const resize = model3?.inputLimits?.images?.resize; + const model2 = ref === void 0 ? void 0 : api2.models.getModel(ref.provider, ref.modelId); + const resize = model2?.inputLimits?.images?.resize; return { - vision: model3?.input.includes("image") ?? true, + vision: model2?.input.includes("image") ?? true, limits: { maxWidth: resize?.maxWidth ?? DEFAULT_IMAGE_LIMITS.maxWidth, maxHeight: resize?.maxHeight ?? DEFAULT_IMAGE_LIMITS.maxHeight, @@ -68695,8 +68702,8 @@ var path4 = (cwd, input) => { } return "/" + parts.join("/"); }; -function environment(cwd = "/", conversation, invocation) { - const conversations = Array.isArray(conversation) ? conversation : conversation === void 0 ? [] : [String(conversation)]; +function environment(cwd = "/", conversation2, invocation) { + const conversations = Array.isArray(conversation2) ? conversation2 : conversation2 === void 0 ? [] : [String(conversation2)]; const tag = invocation && { id: invocation.id, pid: 0, program: invocation.tool, conversations }; const call = (kind, p, bytes2 = []) => ops.op_file(kind, path4(cwd, p), bytes2, tag); const env = { @@ -68904,8 +68911,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -69011,8 +69018,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -69103,20 +69110,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -69152,9 +69159,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -69162,8 +69169,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -69181,10 +69188,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -69228,24 +69235,24 @@ var SqliteStorage = class _SqliteStorage { const id = context === void 0 ? idFromNumber(idOrConversationId) : typeof idOrContext === "number" ? idFromNumber(idOrContext) : void 0; if (id === void 0) throw new StorageRequestError("Storage.entry() requires an entry ID"); - let conversation; + let conversation2; if (context !== void 0) { const conversationId = idFromNumber(idOrConversationId); - conversation = await this.readConversation(conversationId); - if (conversation === void 0) + conversation2 = await this.readConversation(conversationId); + if (conversation2 === void 0) throw new StorageRequestError(`Unknown conversation: ${conversationId}`); } const row = await this.db.get(`SELECT record, commit_seq FROM ${this.schema.tables.entries} WHERE id = ?`, id); if (row === void 0) return void 0; const entry2 = parseJson(row.record); - if (conversation !== void 0) { + if (conversation2 !== void 0) { let upperEntryId = Number.POSITIVE_INFINITY; - while (conversation.id !== entry2.conversationId) { - if (conversation.parent === void 0) + while (conversation2.id !== entry2.conversationId) { + if (conversation2.parent === void 0) return void 0; - upperEntryId = Math.min(upperEntryId, conversation.parent.at); - conversation = await this.readConversation(conversation.parent.conversationId); + upperEntryId = Math.min(upperEntryId, conversation2.parent.at); + conversation2 = await this.readConversation(conversation2.parent.conversationId); } if (entry2.id > upperEntryId) return void 0; @@ -69253,26 +69260,26 @@ var SqliteStorage = class _SqliteStorage { return { entry: entry2, commitSeq: seqFromNumber(row.commit_seq) }; } async readLatestHeadMarker(conversationId, atOrBeforeEntryId) { - let conversation = await this.readConversation(conversationId); - if (conversation === void 0) + let conversation2 = await this.readConversation(conversationId); + if (conversation2 === void 0) throw new StorageRequestError(`Unknown conversation: ${conversationId}`); let upper = atOrBeforeEntryId; while (true) { - const row = upper === void 0 ? await this.db.get(`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL ORDER BY id DESC LIMIT 1`, conversation.id) : await this.db.get(`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL AND id <= ? ORDER BY id DESC LIMIT 1`, conversation.id, upper); + const row = upper === void 0 ? await this.db.get(`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL ORDER BY id DESC LIMIT 1`, conversation2.id) : await this.db.get(`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL AND id <= ? ORDER BY id DESC LIMIT 1`, conversation2.id, upper); if (row !== void 0) return parseJson(row.record); - if (conversation.parent === void 0) + if (conversation2.parent === void 0) return void 0; - upper = upper === void 0 ? conversation.parent.at : Math.min(upper, conversation.parent.at); - conversation = await this.readConversation(conversation.parent.conversationId); + upper = upper === void 0 ? conversation2.parent.at : Math.min(upper, conversation2.parent.at); + conversation2 = await this.readConversation(conversation2.parent.conversationId); } } async readEntries(query, limit3, cursor) { const { order, after } = scanStart(query.order, cursor, "descending"); if (order === "ascending") return this.readEntriesAscending(query, limit3, after); - let conversation = await this.readConversation(query.conversationId); - if (conversation === void 0) + let conversation2 = await this.readConversation(query.conversationId); + if (conversation2 === void 0) throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`); let upper = query.maxEntryId; if (after !== void 0) @@ -69280,7 +69287,7 @@ var SqliteStorage = class _SqliteStorage { const values = []; while (true) { const clauses = ["conversation_id = ?"]; - const params = [conversation.id]; + const params = [conversation2.id]; if (query.minEntryId !== void 0) { clauses.push("id >= ?"); params.push(query.minEntryId); @@ -69292,30 +69299,30 @@ var SqliteStorage = class _SqliteStorage { params.push(limit3 + 1 - values.length); const rows = await this.db.all(`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(" AND ")} ORDER BY id DESC LIMIT ?`, ...params); values.push(...rows.map((row) => parseJson(row.record))); - if (values.length > limit3 || conversation.parent === void 0) + if (values.length > limit3 || conversation2.parent === void 0) break; - upper = upper === void 0 ? conversation.parent.at : Math.min(upper, conversation.parent.at); + upper = upper === void 0 ? conversation2.parent.at : Math.min(upper, conversation2.parent.at); if (query.minEntryId !== void 0 && upper < query.minEntryId) break; - conversation = await this.readConversation(conversation.parent.conversationId); + conversation2 = await this.readConversation(conversation2.parent.conversationId); } return page2(values, limit3, "descending"); } /** Oldest first: the fork chain's segments from the root conversation forward, each up to its fork point. */ async readEntriesAscending(query, limit3, after) { const segments = []; - let conversation = await this.readConversation(query.conversationId); - if (conversation === void 0) + let conversation2 = await this.readConversation(query.conversationId); + if (conversation2 === void 0) throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`); let upper = query.maxEntryId; while (true) { - segments.push({ conversationId: conversation.id, upper }); - if (conversation.parent === void 0) + segments.push({ conversationId: conversation2.id, upper }); + if (conversation2.parent === void 0) break; - upper = upper === void 0 ? conversation.parent.at : Math.min(upper, conversation.parent.at); + upper = upper === void 0 ? conversation2.parent.at : Math.min(upper, conversation2.parent.at); if (query.minEntryId !== void 0 && upper < query.minEntryId) break; - conversation = await this.readConversation(conversation.parent.conversationId); + conversation2 = await this.readConversation(conversation2.parent.conversationId); } let lower = query.minEntryId; if (after !== void 0) @@ -69620,7 +69627,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -69628,7 +69635,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -69673,21 +69680,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -69697,12 +69704,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -69778,9 +69785,9 @@ var Wait = defineTask({ await runtime.sleepUntil(Date.now() + 1e3, { phase: "wait" }, context); return; } - const conversation = await runtime.conversation(runtime.conversationId, context); + const conversation2 = await runtime.conversation(runtime.conversationId, context); await runtime.commit(async (tx) => { - await conversation.submit(tx, { type: "input", content: request2.message, requestId: `credential:${request2.id}` }); + await conversation2.submit(tx, { type: "input", content: request2.message, requestId: `credential:${request2.id}` }); return { status: "terminal", outcome: { status: "completed", result: null } }; }, context); } @@ -69790,10 +69797,10 @@ var Wait = defineTask({ var CredentialRequests = defineExtension({ name: "sausage.credentials", tasks: [Wait] }); async function discoverRequests(harness2, context) { for (const request2 of Deno.core.ops.op_credential_requests()) { - const conversation = await harness2.conversation(Number(request2.conversation), context); - if (!conversation) continue; - await conversation.commit(async (tx) => { - const recorded = await tx.doc(Requests, conversation.id); + const conversation2 = await harness2.conversation(Number(request2.conversation), context); + if (!conversation2) continue; + await conversation2.commit(async (tx) => { + const recorded = await tx.doc(Requests, conversation2.id); if (recorded.ids.includes(request2.id)) return; await tx.createTask(Wait, { id: request2.id }, { ownership: { kind: "conversation" }, background: true }); recorded.ids.push(request2.id); @@ -69816,7 +69823,7 @@ async function startRequests(harness2, context) { } // input.ts -async function serve(harness2, context, afterSubmit, api2) { +async function serve(harness2, context, afterSubmit, api2, defaultConversation) { const pending = /* @__PURE__ */ new Set(); const track2 = (work) => { const task = work.catch((error) => Deno.core.ops.op_output(`${String(error)} @@ -69839,9 +69846,10 @@ async function serve(harness2, context, afterSubmit, api2) { track2(api2.handle(input)); continue; } - const conversation = await harness2.conversation(input.conversation, context); - if (!conversation) throw new Error(`Unknown conversation: ${input.conversation}`); - const submission2 = await conversation.submit({ + const id = defaultConversation ? await defaultConversation() : input.conversation; + const conversation2 = await harness2.conversation(id, context); + if (!conversation2) throw new Error(`Unknown conversation: ${id}`); + const submission2 = await conversation2.submit({ type: "input", content: input.content, requestId: input.requestId @@ -69855,9 +69863,6649 @@ async function serve(harness2, context, afterSubmit, api2) { } } -// node_modules/@earendil-works/pi-ai/dist/index.js +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify5, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js var dist_exports4 = {}; __export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify5, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path5) { + const ctrl = callVisitor(key, node, visitor, path5); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path5, ctrl); + return visit_(key, ctrl, visitor, path5); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path5 = Object.freeze(path5.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path5); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path5 = Object.freeze(path5.concat(node)); + const ck = visit_("key", node.key, visitor, path5); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path5); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path5) { + const ctrl = await callVisitor(key, node, visitor, path5); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path5, ctrl); + return visitAsync_(key, ctrl, visitor, path5); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path5 = Object.freeze(path5.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path5); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path5 = Object.freeze(path5.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path5); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path5); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path5) { + if (typeof visitor === "function") + return visitor(key, node, path5); + if (isMap(node)) + return visitor.Map?.(key, node, path5); + if (isSeq(node)) + return visitor.Seq?.(key, node, path5); + if (isPair(node)) + return visitor.Pair?.(key, node, path5); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path5); + if (isAlias(node)) + return visitor.Alias?.(key, node, path5); + return void 0; +} +function replaceNode(key, path5, node) { + const parent = path5[path5.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path5, value2) { + let v = value2; + for (let i = path5.length - 1; i >= 0; --i) { + const k = path5[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path5) => path5 == null || typeof path5 === "object" && !!path5[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path5, value2) { + if (isEmptyPath(path5)) + this.add(value2); + else { + const [key, ...rest] = path5; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path5) { + const [key, ...rest] = path5; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path5, keepScalar) { + const [key, ...rest] = path5; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path5) { + const [key, ...rest] = path5; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path5, value2) { + const [key, ...rest] = path5; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text2, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text2; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text2.length <= endStep) + return text2; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text2, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text2[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text2[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text2, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text2[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text2[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text2; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text2; + if (onFold) + onFold(); + let res = text2.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text2.length; + if (fold === 0) + res = ` +${indent}${text2.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text2[fold]}\\`; + res += ` +${indent}${text2.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text2, i, indent) { + let end = i; + let start = i + 1; + let ch = text2[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text2[++i]; + } else { + do { + ch = text2[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text2[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit3 = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit3) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit3) + return true; + start = i + 1; + if (strLen - start <= limit3) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify3(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify3(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify3(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify6 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify6(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify3(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify3(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify3(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify3(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path5, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path5, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path5) { + if (isEmptyPath(path5)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path5) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path5, keepScalar) { + if (isEmptyPath(path5)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path5, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path5) { + if (isEmptyPath(path5)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path5) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path5, value2) { + if (isEmptyPath(path5)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path5), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path5, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines2(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines2(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok2 = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok2 ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify4, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify4 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path5) => { + let item = cst; + for (const [field, index] of path5) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path5) => { + const parent = visit2.itemAtPath(cst, path5.slice(0, -1)); + const field = path5[path5.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path5, item, visitor) { + let ctrl = visitor(item, path5); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path5.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path5); + } + } + return typeof ctrl === "function" ? ctrl(item, path5) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state2) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state2; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs3 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs3, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs3); + } else { + Object.assign(it, { key: fs3, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs3 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs3, sep: [] }); + else if (it.sep) + this.stack.push(fs3); + else + Object.assign(it, { key: fs3, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify5(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + +// node_modules/@earendil-works/pi-ai/dist/index.js +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -70121,13 +76769,13 @@ function cloneMessage(message, api2, provider2, modelId) { usage: cloned.usage ?? DEFAULT_USAGE }; } -function createDeferredMessage(model3, handle) { +function createDeferredMessage(model2, handle) { return { role: "assistant", content: [], - api: model3.api, - provider: model3.provider, - model: model3.id, + api: model2.api, + provider: model2.provider, + model: model2.id, usage: DEFAULT_USAGE, stopReason: "deferred", deferred: handle, @@ -70517,11 +77165,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted2; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -70701,7 +77349,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports4, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports4, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -70930,7 +77578,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state2 }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state2 }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -70961,11 +77614,11 @@ function harnessApi(harness2, models2, extensions2, context) { const streams = /* @__PURE__ */ new Map(); const log = eventLog(() => harness2).eventLog; const send = (id, value2) => Deno.core.ops.op_harness_reply(id, value2); - async function entries2(conversation, after) { + async function entries2(conversation2, after) { const found = []; let cursor; do { - const page3 = await conversation.entries({ minEntryId: after + 1, order: "ascending" }, 256, cursor, context); + const page3 = await conversation2.entries({ minEntryId: after + 1, order: "ascending" }, 256, cursor, context); found.push(...page3.items); cursor = page3.next; } while (cursor); @@ -71012,6 +77665,7 @@ function harnessApi(harness2, models2, extensions2, context) { }; try { if (input.method === "GET" && path5 === "/conversations") { + const standing2 = await extensions2.standing?.() ?? null; const records = await harness2.commit(async (tx) => { const all = []; let cursor; @@ -71030,7 +77684,7 @@ function harnessApi(harness2, models2, extensions2, context) { const started = await harness2.snapshot(Started2, record2.id, context); return { ...record2, title: metadata?.title ?? "", agent, starter: started?.by ?? null, concluded: concluded.has(record2.id), running: !!live?.run }; })); - reply(200, { conversations }); + reply(200, { conversations, standing: standing2 }); return; } if (input.method === "GET" && path5 === "/events") { @@ -71042,16 +77696,6 @@ function harnessApi(harness2, models2, extensions2, context) { reply(200, extensions2.state()); return; } - if (input.method === "GET" && path5 === "/families") { - let families = {}; - try { - families = JSON.parse(await fs2.read("/src/sausage/agents/models.json")); - } catch (error) { - if (error.code !== "not_found") throw error; - } - reply(200, { families }); - return; - } if (input.method === "GET" && path5 === "/models") { reply(200, { models: models2.getAllModels().map(({ id, name, provider: provider2, contextWindow, maxTokens, reasoning, cost }) => ({ id, name, provider: provider2, contextWindow, maxTokens, reasoning, cost })) }); return; @@ -71066,26 +77710,26 @@ function harnessApi(harness2, models2, extensions2, context) { } const match = /^\/conversations\/(\d+)\/(entries|stream|submit|stop)$/.exec(path5); if (!match) fail(404, "Unknown harness route"); - const conversation = await harness2.conversation(integer(match[1]), context); - if (!conversation) fail(404, "Unknown conversation"); + const conversation2 = await harness2.conversation(integer(match[1]), context); + if (!conversation2) fail(404, "Unknown conversation"); const after = integer(url.searchParams.get("after"), 0); if (input.method === "GET" && match[2] === "entries") { - reply(200, { entries: await entries2(conversation, after) }); + reply(200, { entries: await entries2(conversation2, after) }); return; } if (input.method === "GET" && match[2] === "stream") { - await follow(input, (cursor) => entries2(conversation, cursor), after); + await follow(input, (cursor) => entries2(conversation2, cursor), after); return; } if (input.method === "POST" && match[2] === "submit") { if (typeof data.requestId !== "string" || !data.requestId || typeof data.content !== "string" || !data.content.trim()) fail(400, "Expected content and requestId"); - const submission2 = await conversation.submit({ type: "input", content: data.content, requestId: data.requestId }, context); + const submission2 = await conversation2.submit({ type: "input", content: data.content, requestId: data.requestId }, context); reply(202, { submissionId: submission2.id }); return; } if (input.method === "POST" && match[2] === "stop") { for (; ; ) { - const own = (await harness2.inspect(context)).tasks.filter(({ record: record2 }) => record2.conversationId === conversation.id && !record2.owner && !record2.background); + const own = (await harness2.inspect(context)).tasks.filter(({ record: record2 }) => record2.conversationId === conversation2.id && !record2.owner && !record2.background); if (!own.length) break; for (const { record: record2 } of own) { await harness2.abortTask(record2.id, context); @@ -71106,10 +77750,8 @@ function harnessApi(harness2, models2, extensions2, context) { } // main.ts -var proxy = Deno.core.ops.op_model_proxy(); -if (!proxy?.base_url || !proxy?.api_key) throw new Error("The llm-proxy credential is required"); -var models = await proxyModels(proxy); -var model2 = models.getModel("openai", "gpt-6.1-sol"); +var proxy = await Deno.core.ops.op_model_proxy(); +var models = await proxyModels(proxy, () => Deno.core.ops.op_model_proxy()); var registry2 = createRegistry(); registry2.install(CodingTools2); registry2.install(CredentialRequests); @@ -71123,12 +77765,13 @@ var harness = await Harness.open(storage, { env: async (target) => environment(target.cwd ?? "/", await chain(target.conversationId)) }, BACKGROUND_CONTEXT); var chain = conversationChains(harness, BACKGROUND_CONTEXT); -var root = await harness.root(BACKGROUND_CONTEXT, { agent: { model: { provider: "openai", modelId: model2.id }, thinkingLevel: "low", cwd: "/" } }); -var storedAgent = await harness.snapshot(AgentDoc, root.id, BACKGROUND_CONTEXT); -if (Array.isArray(storedAgent?.extensions) && storedAgent.extensions.length === 2 && [CodingTools2, CredentialRequests].every((extension) => storedAgent.extensions.includes(extension.name))) { - await root.configure({ extensions: null }, BACKGROUND_CONTEXT); -} -var watch = await root.watch(BACKGROUND_CONTEXT); +await harness.root(BACKGROUND_CONTEXT, { agent: { cwd: "/src/sausage" } }); +var stopRequests = await startRequests(harness, BACKGROUND_CONTEXT); +var extensions = await loadExtensions(harness, registry2, storage, models, BACKGROUND_CONTEXT, [CodingTools2, CredentialRequests]); +var standing = await extensions.standing(); +if (!standing) throw new Error("The world needs the models and subagents extensions for its standing agent"); +var conversation = await harness.conversation(standing.conversationId, BACKGROUND_CONTEXT); +var watch = await conversation.watch(BACKGROUND_CONTEXT); var emitted = /* @__PURE__ */ new Map(); var partial = ""; var text = (message) => message?.content?.filter((b) => b.type === "text").map((b) => b.text).join("") ?? ""; @@ -71152,17 +77795,15 @@ for (const entry2 of watch.value.entries) { if (globalThis.consoleEnabled) watch.start((event) => { if (event.kind === "value") render(event.value); }); -var stopRequests = await startRequests(harness, BACKGROUND_CONTEXT); -var extensions = await loadExtensions(harness, registry2, storage, models, BACKGROUND_CONTEXT, [CodingTools2, CredentialRequests]); var api = harnessApi(harness, models, extensions, BACKGROUND_CONTEXT); harness.resume(); await serve(harness, BACKGROUND_CONTEXT, globalThis.consoleEnabled ? async () => { await harness.waitForIdle(BACKGROUND_CONTEXT); - const final = await root.watch(BACKGROUND_CONTEXT); + const final = await conversation.watch(BACKGROUND_CONTEXT); render(final.value); await final.stop(); Deno.core.ops.op_output("\n"); -} : void 0, api); +} : void 0, api, async () => (await extensions.standing()).conversationId); await api.close(); await extensions.close(); await stopRequests(); diff --git a/host/js/chain-test-bundle.js b/host/js/chain-test-bundle.js index 44e1c25..27ef2dc 100644 --- a/host/js/chain-test-bundle.js +++ b/host/js/chain-test-bundle.js @@ -259,16 +259,16 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js function createTypedMetrics(metrics, schemas) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -314,8 +314,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -523,7 +523,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -540,7 +540,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -2869,12 +2869,12 @@ function arr(items, options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -2942,8 +2942,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3019,10 +3019,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3032,12 +3032,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base, fragment) { let node = root2; @@ -3124,9 +3124,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3188,26 +3188,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3222,7 +3222,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3231,10 +3231,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3340,8 +3340,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -3354,7 +3354,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3364,11 +3364,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -3382,19 +3382,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3406,9 +3406,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -3422,12 +3422,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3435,7 +3435,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3443,31 +3443,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -3563,11 +3563,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -3960,9 +3960,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4221,9 +4221,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4289,9 +4289,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4302,7 +4302,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -4711,9 +4711,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5065,9 +5065,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check) : new Validator(schema, options, check); +function compile(schema4, options = NO_OPTIONS) { + const check = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check) : new Validator(schema4, options, check); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5076,9 +5076,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check) { + constructor(schema4, options, check) { this.check = check; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5110,18 +5110,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -8590,19 +8590,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -9361,14 +9361,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record = { ...record, retiredAt: seq }; + record = { ...record, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -9816,8 +9816,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -9850,8 +9850,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -9869,7 +9869,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -10729,7 +10729,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -10739,15 +10739,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -10758,7 +10758,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -10771,7 +10771,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -10840,7 +10840,7 @@ var SessionImpl = class { const conversationId = record.scope.kind === "conversation" ? record.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -10848,7 +10848,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -10903,7 +10903,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -10931,9 +10931,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -11564,7 +11564,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -11572,27 +11572,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -12141,7 +12141,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -12149,7 +12149,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -12564,21 +12564,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -12620,14 +12620,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -12654,9 +12654,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence >> 37n & 0x0fn); bytes2[7] = Number(sequence >> 29n & 0xffn); @@ -12835,12 +12835,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -12854,16 +12854,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -15448,20 +15448,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record) => [record.id, record.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record, name) { const memos = record?.memos; @@ -16369,13 +16369,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -16970,18 +16970,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -17161,7 +17161,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -17175,7 +17175,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -21415,6 +21415,2273 @@ function environment(cwd = "/", conversation, invocation) { return env; } +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path2) { + const ctrl = callVisitor(key, node, visitor, path2); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path2, ctrl); + return visit_(key, ctrl, visitor, path2); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path2 = Object.freeze(path2.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path2); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path2 = Object.freeze(path2.concat(node)); + const ck = visit_("key", node.key, visitor, path2); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path2); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path2) { + const ctrl = await callVisitor(key, node, visitor, path2); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path2, ctrl); + return visitAsync_(key, ctrl, visitor, path2); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path2 = Object.freeze(path2.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path2); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path2 = Object.freeze(path2.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path2); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path2); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path2) { + if (typeof visitor === "function") + return visitor(key, node, path2); + if (isMap(node)) + return visitor.Map?.(key, node, path2); + if (isSeq(node)) + return visitor.Seq?.(key, node, path2); + if (isPair(node)) + return visitor.Pair?.(key, node, path2); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path2); + if (isAlias(node)) + return visitor.Alias?.(key, node, path2); + return void 0; +} +function replaceNode(key, path2, node) { + const parent = path2[path2.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path2, value2) { + let v = value2; + for (let i = path2.length - 1; i >= 0; --i) { + const k = path2[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path2) => path2 == null || typeof path2 === "object" && !!path2[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path2, value2) { + if (isEmptyPath(path2)) + this.add(value2); + else { + const [key, ...rest] = path2; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path2) { + const [key, ...rest] = path2; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path2, keepScalar) { + const [key, ...rest] = path2; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path2) { + const [key, ...rest] = path2; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path2, value2) { + const [key, ...rest] = path2; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path2) => { + let item = cst; + for (const [field, index] of path2) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path2) => { + const parent = visit2.itemAtPath(cst, path2.slice(0, -1)); + const field = path2[path2.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path2, item, visitor) { + let ctrl = visitor(item, path2); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path2.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path2); + } + } + return typeof ctrl === "function" ? ctrl(item, path2) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); + // events.ts function defineEvent(name, options = {}) { const kind = `event.${name}`; @@ -21585,8 +23852,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -21692,8 +23959,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -21784,20 +24051,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -21833,9 +24100,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -21843,8 +24110,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -21862,10 +24129,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -22301,7 +24568,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -22309,7 +24576,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -22354,21 +24621,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record; if (action.create !== void 0) { record = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record = parseJson(row.record); @@ -22378,12 +24645,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record = { ...record, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record), id); + record = { ...record, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record), id); } if (isCurrentOnly(record)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); diff --git a/host/js/core-ext-test-bundle.js b/host/js/core-ext-test-bundle.js index c29fe05..5ad929f 100644 --- a/host/js/core-ext-test-bundle.js +++ b/host/js/core-ext-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root, base, fragment) { let node = root; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -20108,7 +20108,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28718,8 +28718,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -28825,8 +28825,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -28917,20 +28917,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -28966,9 +28966,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -28976,8 +28976,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -28995,10 +28995,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -29434,7 +29434,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -29442,7 +29442,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -29487,21 +29487,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -29511,12 +29511,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -29571,6 +29571,6646 @@ async function openStorage(path) { return SqliteStorage.open(database); } +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -30007,7 +36647,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -30132,7 +36772,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -31043,8 +37683,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -31246,11 +37886,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -31467,7 +38107,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -31696,7 +38336,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -31734,17 +38379,41 @@ var loader = await loadExtensions(harness, registry, storage, models, BACKGROUND try { assert(!loader.state().error, `loader: ${loader.state().error ?? "loaded"}`); const { selection, conversations, State, metadata } = globalThis.core; + const config = parse(await fs.read("/etc/sausage/config.yaml")); + config.standing = "worker"; + config.roster = [{ name: "worker", description: "Worker", model: "faux/faux-1", thinking: "low", tools: ["read", "write"], prompt: "Worker body" }]; + const save = () => fs.write("/etc/sausage/config.yaml", JSON.stringify(config)); + await save(); const worker = await selection.start({ agent: "worker", cwd: "/project/sub" }, BACKGROUND_CONTEXT); let agent = await worker.agent(BACKGROUND_CONTEXT); - assert(agent.model.modelId === "faux-1" && agent.thinkingLevel === "low", "worker fast family and thinking"); - assert(agent.tools.map((t) => t.name).join(",") === "read,write", "worker tools and project overlay"); - assert(agent.instructions.includes("Worker body") && agent.instructions.includes("Project body"), "definition body and overlay"); + assert(agent.model.modelId === "faux-1" && agent.thinkingLevel === "low", "worker roster model and thinking"); + assert(agent.tools.map((t) => t.name).join(",") === "read,write", "worker roster tools"); + assert(agent.instructions.indexOf("## Sausage and the world") < agent.instructions.indexOf("Worker body"), "global prompt precedes role prompt"); const sections = {}; for (const section2 of agent.sections) sections[section2.key] = await section2.render({ conversationId: worker.id, agent }, BACKGROUND_CONTEXT); assert(sections.project_context.includes("Root instructions") && sections.project_context.includes("Nested instructions"), "cwd and parent AGENTS.md"); assert(!sections.project_context.includes("Outside instructions"), "instructions stop at repo root"); assert(sections.skills.includes("builtin-skill") && sections.skills.includes("project-skill"), "builtin and project skills"); assert(sections.cwd === "/project/sub" && sections.tools.includes("read"), "cwd and tools sections"); + const checkPrompt = (ctx, expected) => { + const prompt = JSON.stringify(ctx.messages.filter((message) => message.role === "system")); + for (const route of ["whoami", "conversations/ID/entries?after=N", "events?after=N", "models", "extensions", "credential-requests", "/proc/processes", "/proc/extensions", "jaq"]) assert(prompt.includes(route), `fresh system prompt includes ${route}`); + assert(prompt.includes(expected), "system prompt uses current global prompt"); + assert(prompt.indexOf(expected) < prompt.indexOf("Worker body"), "system prompt places global prompt before role prompt"); + }; + faux.setResponses([(ctx) => { + checkPrompt(ctx, "## Sausage and the world"); + return fauxAssistantMessage("fresh"); + }]); + harness.resume(); + await (await worker.submit({ type: "input", content: "fresh" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); + config.prompt = "Edited global prompt\\n" + config.prompt; + await save(); + faux.setResponses([(ctx) => { + checkPrompt(ctx, "Edited global prompt"); + return fauxAssistantMessage("edited"); + }]); + await (await worker.submit({ type: "input", content: "edited" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); const seed = await harness.commit((tx) => tx.appendEntry(worker.id, { kind: "test.seed" }), BACKGROUND_CONTEXT); const child = await worker.fork(seed.id, { ownership: { kind: "ownerless" } }, BACKGROUND_CONTEXT); const unrelated = await harness.createConversation({ ownership: { kind: "ownerless" } }, BACKGROUND_CONTEXT); @@ -31763,29 +38432,33 @@ try { assert(JSON.stringify([...await conversations.concluded(BACKGROUND_CONTEXT)]) === JSON.stringify([unrelated.id]), "input placement atomically resumes ancestors"); harness.resume(); await receipt.wait(BACKGROUND_CONTEXT); - await fs.write("/src/sausage/agents/models.json", JSON.stringify({ default: { model: "faux/faux-1" }, fast: { model: "faux/faux-1", thinking: "high" } })); + config.roster[0].thinking = "high"; + await save(); faux.setResponses([fauxAssistantMessage("next")]); await (await worker.submit({ type: "input", content: "next" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); agent = await worker.agent(BACKGROUND_CONTEXT); assert(agent.thinkingLevel === "high", "model config edit applies next turn"); const provider2 = models.getProvider("faux"), template = models.getModels("faux")[0]; models.setProvider({ ...provider2, getModels: () => [template, { ...template, id: "second" }] }); - await fs.write("/src/sausage/agents/models.json", JSON.stringify({ default: { model: "faux/faux-1" }, fast: { model: "faux/second" } })); + config.roster[0].model = "faux/second"; + await save(); faux.setResponses([fauxAssistantMessage("second")]); await (await worker.submit({ type: "input", content: "second" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); - assert((await harness.snapshot(AgentDoc, worker.id, BACKGROUND_CONTEXT)).model.modelId === "second", "edited family changes next model without restart"); - await fs.write("/src/sausage/agents/models.json", JSON.stringify({ default: { model: "faux/faux-1" }, fast: { model: "openai/new" } })); + assert((await harness.snapshot(AgentDoc, worker.id, BACKGROUND_CONTEXT)).model.modelId === "second", "edited roster changes next model without restart"); + config.roster[0].model = "openai/new"; + await save(); faux.setResponses([fauxAssistantMessage("proxy")]); await (await worker.submit({ type: "input", content: "proxy" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); assert(models.getModel("openai", "new").baseUrl === proxyTemplate.baseUrl && models.getModel("openai", "new").cost.input === 0 && models.getProvider("openai").auth === proxyAuth, "new model retains proxy transport and auth"); - await fs.write("/src/sausage/agents/models.json", JSON.stringify({ default: { model: "faux/faux-1" }, fast: { model: "anthropic/new" } })); + config.roster[0].model = "anthropic/new"; + await save(); faux.setResponses([fauxAssistantMessage("anthropic")]); await (await worker.submit({ type: "input", content: "anthropic" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); assert(models.getModel("anthropic", "new").baseUrl === "https://proxy.invalid/apis/anthropic", "new Anthropic model retains its own provider transport"); globalThis.modelPin = { provider: "faux", modelId: "faux-1" }; faux.setResponses([fauxAssistantMessage("pin")]); await (await worker.submit({ type: "input", content: "pin" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); - assert((await worker.agent(BACKGROUND_CONTEXT)).model.provider === "faux", "models.pin overrides family selection"); + assert((await worker.agent(BACKGROUND_CONTEXT)).model.provider === "faux", "models.pin overrides roster selection"); await harness.commit((tx) => conversations.setStanding(tx, worker.id, true), BACKGROUND_CONTEXT); let refused = false; try { diff --git a/host/js/core-ext-test.ts b/host/js/core-ext-test.ts index 134f124..9cf5a46 100644 --- a/host/js/core-ext-test.ts +++ b/host/js/core-ext-test.ts @@ -5,6 +5,7 @@ import { fauxProvider, fauxAssistantMessage } from '@earendil-works/pi-ai/provid import { Harness, AgentDoc, createRegistry } from '@earendil-works/pi-durable' import { openStorage } from './sqlite' import { loadExtensions, fs } from './extensions' +import { parse } from 'yaml' const assert = (ok:any,message:string)=>{if(!ok)throw new Error(message);Deno.core.ops.op_output(`ok - ${message}\n`)} const models=createModels(), faux=fauxProvider({tokensPerSecond:100000});models.setProvider(faux.provider) const proxyTemplate={...models.getModels('faux')[0],provider:'openai',baseUrl:'https://proxy.invalid/v1'} @@ -18,17 +19,35 @@ const loader=await loadExtensions(harness,registry,storage,models,context) try { assert(!loader.state().error,`loader: ${loader.state().error ?? 'loaded'}`) const {selection,conversations,State,metadata}=globalThis.core + const config = parse(await fs.read('/etc/sausage/config.yaml')) + config.standing='worker' + config.roster=[{name:'worker',description:'Worker',model:'faux/faux-1',thinking:'low',tools:['read','write'],prompt:'Worker body'}] + const save = ()=>fs.write('/etc/sausage/config.yaml',JSON.stringify(config)) + await save() const worker=await selection.start({agent:'worker',cwd:'/project/sub'},context) let agent=await worker.agent(context) - assert(agent.model.modelId==='faux-1' && agent.thinkingLevel==='low','worker fast family and thinking') - assert(agent.tools.map(t=>t.name).join(',')==='read,write','worker tools and project overlay') - assert(agent.instructions.includes('Worker body') && agent.instructions.includes('Project body'),'definition body and overlay') + assert(agent.model.modelId==='faux-1' && agent.thinkingLevel==='low','worker roster model and thinking') + assert(agent.tools.map(t=>t.name).join(',')==='read,write','worker roster tools') + assert(agent.instructions.indexOf('## Sausage and the world') < agent.instructions.indexOf('Worker body'),'global prompt precedes role prompt') const sections:any={} for(const section of agent.sections) sections[section.key]=await section.render({conversationId:worker.id,agent},context) assert(sections.project_context.includes('Root instructions') && sections.project_context.includes('Nested instructions'),'cwd and parent AGENTS.md') assert(!sections.project_context.includes('Outside instructions'),'instructions stop at repo root') assert(sections.skills.includes('builtin-skill') && sections.skills.includes('project-skill'),'builtin and project skills') assert(sections.cwd==='/project/sub' && sections.tools.includes('read'),'cwd and tools sections') + const checkPrompt = (ctx: any, expected: string) => { + const prompt=JSON.stringify(ctx.messages.filter((message: any)=>message.role==='system')) + for (const route of ['whoami','conversations/ID/entries?after=N','events?after=N','models','extensions','credential-requests','/proc/processes','/proc/extensions','jaq']) assert(prompt.includes(route),`fresh system prompt includes ${route}`) + assert(prompt.includes(expected),'system prompt uses current global prompt') + assert(prompt.indexOf(expected){checkPrompt(ctx,'## Sausage and the world');return fauxAssistantMessage('fresh')}]) + harness.resume() + await (await worker.submit({type:'input',content:'fresh'},context)).wait(context) + config.prompt='Edited global prompt\\n'+config.prompt + await save() + faux.setResponses([(ctx)=>{checkPrompt(ctx,'Edited global prompt');return fauxAssistantMessage('edited')}]) + await (await worker.submit({type:'input',content:'edited'},context)).wait(context) const seed=await harness.commit(tx=>tx.appendEntry(worker.id,{kind:'test.seed'}),context) const child=await worker.fork(seed.id,{ownership:{kind:'ownerless'}},context) const unrelated=await harness.createConversation({ownership:{kind:'ownerless'}},context) @@ -46,7 +65,7 @@ try { const receipt=await child.submit({type:'input',content:'resume'},context) assert(JSON.stringify([...await conversations.concluded(context)])===JSON.stringify([unrelated.id]),'input placement atomically resumes ancestors') harness.resume();await receipt.wait(context) - await fs.write('/src/sausage/agents/models.json',JSON.stringify({default:{model:'faux/faux-1'},fast:{model:'faux/faux-1',thinking:'high'}})) + config.roster[0].thinking='high';await save() faux.setResponses([fauxAssistantMessage('next')]) await (await worker.submit({type:'input',content:'next'},context)).wait(context) agent=await worker.agent(context) @@ -54,22 +73,22 @@ try { // A second faux model proves selection changes, not only the thinking level. const provider=models.getProvider('faux'), template=models.getModels('faux')[0] models.setProvider({...provider,getModels:()=>[template,{...template,id:'second'}]}) - await fs.write('/src/sausage/agents/models.json',JSON.stringify({default:{model:'faux/faux-1'},fast:{model:'faux/second'}})) + config.roster[0].model='faux/second';await save() faux.setResponses([fauxAssistantMessage('second')]) await (await worker.submit({type:'input',content:'second'},context)).wait(context) - assert((await harness.snapshot(AgentDoc,worker.id,context)).model.modelId==='second','edited family changes next model without restart') - await fs.write('/src/sausage/agents/models.json',JSON.stringify({default:{model:'faux/faux-1'},fast:{model:'openai/new'}})) + assert((await harness.snapshot(AgentDoc,worker.id,context)).model.modelId==='second','edited roster changes next model without restart') + config.roster[0].model='openai/new';await save() faux.setResponses([fauxAssistantMessage('proxy')]) await (await worker.submit({type:'input',content:'proxy'},context)).wait(context) assert(models.getModel('openai','new').baseUrl===proxyTemplate.baseUrl && models.getModel('openai','new').cost.input===0 && models.getProvider('openai').auth===proxyAuth,'new model retains proxy transport and auth') - await fs.write('/src/sausage/agents/models.json',JSON.stringify({default:{model:'faux/faux-1'},fast:{model:'anthropic/new'}})) + config.roster[0].model='anthropic/new';await save() faux.setResponses([fauxAssistantMessage('anthropic')]) await (await worker.submit({type:'input',content:'anthropic'},context)).wait(context) assert(models.getModel('anthropic','new').baseUrl==='https://proxy.invalid/apis/anthropic','new Anthropic model retains its own provider transport') globalThis.modelPin={provider:'faux',modelId:'faux-1'} faux.setResponses([fauxAssistantMessage('pin')]) await (await worker.submit({type:'input',content:'pin'},context)).wait(context) - assert((await worker.agent(context)).model.provider==='faux','models.pin overrides family selection') + assert((await worker.agent(context)).model.provider==='faux','models.pin overrides roster selection') await harness.commit(tx=>conversations.setStanding(tx,worker.id,true),context) let refused=false;try{await harness.commit(tx=>conversations.concludeIn(tx,[worker.id]),context)}catch{refused=true} assert(refused,'standing conversation cannot conclude') diff --git a/host/js/dream-test-bundle.js b/host/js/dream-test-bundle.js index 56d5ff0..1084d13 100644 --- a/host/js/dream-test-bundle.js +++ b/host/js/dream-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base2, fragment) { let node = root2; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base2) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base2) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base2); + const b = this.baseOf(schema4, base2); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base2, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base2, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base2, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base2, next); + next = this.convert(schema4, base2, next); } if (!matched && additional !== void 0) next = this.convert(additional, base2, next); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base2) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base2) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base2); + const b = this.baseOf(schema4, base2); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base2) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base2) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base2) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base2)); + set2(key, this.coerceTypes(value2[key], property, base2)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base2)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base2)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base2)); + set2(key, this.coerceTypes(value2[key], additional, base2)); } return out ?? value2; } - coerceItems(value2, schema, base2) { + coerceItems(value2, schema4, base2) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base2) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base2, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -20108,7 +20108,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28631,6 +28631,6646 @@ var MemoryStorage = class { } }; +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root2) { + const anchors = /* @__PURE__ */ new Set(); + visit(root2, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -29067,7 +35707,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -29192,7 +35832,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -30103,8 +36743,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -30306,11 +36946,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -30527,7 +37167,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -30756,7 +37396,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -30858,8 +37503,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -30965,8 +37610,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -31057,20 +37702,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -31106,9 +37751,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -31116,8 +37761,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -31135,10 +37780,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -31574,7 +38219,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -31582,7 +38227,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -31627,21 +38272,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -31651,12 +38296,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -31758,7 +38403,7 @@ var { Automations } = await import(`${base}/automations/server.ts`); var { ContextUsageDoc } = await import(`${base}/automations/triggers.ts`); var { Fired } = await import(`${base}/automations/refs.ts`); var { Messages } = await import(`${base}/messages/api.ts`); -var primary = await harness.conversation(await globalThis.dreamSubagents.standing("ultimate", BACKGROUND_CONTEXT), BACKGROUND_CONTEXT); +var primary = await harness.conversation(await globalThis.dreamSubagents.standing("standing", BACKGROUND_CONTEXT), BACKGROUND_CONTEXT); var entries2 = async () => (await primary.context(BACKGROUND_CONTEXT)).entries; var ledger = async () => (await harness.snapshot(Automations, BACKGROUND_CONTEXT))?.automations ?? {}; var requested = async () => (await entries2()).filter((e) => e.kind === "dream.requested"); diff --git a/host/js/dream-test.ts b/host/js/dream-test.ts index 03158e9..c5bf84b 100644 --- a/host/js/dream-test.ts +++ b/host/js/dream-test.ts @@ -35,7 +35,7 @@ const {Automations}=await import(`${base}/automations/server.ts`) const {ContextUsageDoc}=await import(`${base}/automations/triggers.ts`) const {Fired}=await import(`${base}/automations/refs.ts`) const {Messages}=await import(`${base}/messages/api.ts`) -const primary=(await harness.conversation(await globalThis.dreamSubagents.standing('ultimate',context),context))! +const primary=(await harness.conversation(await globalThis.dreamSubagents.standing('standing',context),context))! const entries=async()=> (await primary.context(context)).entries const ledger=async()=> (await harness.snapshot(Automations,context))?.automations??{} const requested=async()=> (await entries()).filter((e:any)=>e.kind==='dream.requested') diff --git a/host/js/events-test-bundle.js b/host/js/events-test-bundle.js index 620c57e..7bb9cc8 100644 --- a/host/js/events-test-bundle.js +++ b/host/js/events-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -576,11 +576,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -596,12 +596,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open: open2, ...annotations } = options; @@ -669,8 +669,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -746,10 +746,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -759,12 +759,12 @@ var Resolver = class { } } load(doc2) { - const schema = this.registry.get(doc2); - if (schema === void 0) + const schema4 = this.registry.get(doc2); + if (schema4 === void 0) return void 0; - this.resources.set(doc2, schema); - this.index(schema, doc2); - return schema; + this.resources.set(doc2, schema4); + this.index(schema4, doc2); + return schema4; } pointer(root, base, fragment) { let node = root; @@ -851,9 +851,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -915,26 +915,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -949,7 +949,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -958,10 +958,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -1067,8 +1067,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -1081,7 +1081,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -1091,11 +1091,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -1109,19 +1109,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -1133,9 +1133,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -1149,12 +1149,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -1162,7 +1162,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -1170,31 +1170,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -1290,11 +1290,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -1687,9 +1687,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -1948,9 +1948,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -2016,9 +2016,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -2029,7 +2029,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -2438,9 +2438,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -2792,9 +2792,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -2803,9 +2803,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -2837,18 +2837,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -2906,7 +2906,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -2929,34 +2929,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -2975,12 +2975,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -2989,22 +2989,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -3012,42 +3012,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -3055,7 +3055,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -3064,16 +3064,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -3086,28 +3086,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -3133,7 +3133,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -3161,7 +3161,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -3369,8 +3369,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -6950,10 +6950,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -6994,11 +6994,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -7062,8 +7062,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -7104,15 +7104,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -7616,8 +7616,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -8088,15 +8088,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -8357,8 +8357,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -8469,16 +8469,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -8495,18 +8495,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service2, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service2.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service2, implementation) { const contract = service2.contract; @@ -8551,13 +8551,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -8566,7 +8566,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -8574,7 +8574,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -8676,15 +8676,15 @@ function dryRun(candidate) { const { run: run2, migrated, service: service2, object } = candidate; const exposed = memberSchemas(service2, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -9050,17 +9050,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -9232,11 +9232,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -11133,10 +11133,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -11163,12 +11163,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -11447,8 +11447,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -11877,11 +11877,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service2, input, principal) { - const { name, input: schema } = service2.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service2.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service2)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -12129,15 +12129,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -13732,19 +13732,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -14503,14 +14503,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -14958,8 +14958,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -14992,8 +14992,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -15011,7 +15011,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -15876,7 +15876,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -15886,15 +15886,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -15905,7 +15905,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -15918,7 +15918,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -15987,7 +15987,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -15995,7 +15995,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -16050,7 +16050,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -16078,9 +16078,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -16711,7 +16711,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -16719,27 +16719,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -17374,7 +17374,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -17382,7 +17382,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -17529,11 +17529,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -17545,14 +17545,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -18518,21 +18518,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -18574,14 +18574,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -18608,9 +18608,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -18789,12 +18789,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -18808,16 +18808,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -21402,20 +21402,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -22323,13 +22323,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -22931,18 +22931,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -23122,7 +23122,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -23136,7 +23136,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -26200,16 +26200,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -26217,14 +26217,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -26262,7 +26262,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -26280,7 +26280,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -26350,9 +26350,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -26695,16 +26695,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -26722,14 +26722,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -26875,7 +26875,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -26892,7 +26892,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -28243,8 +28243,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -28350,8 +28350,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -28442,20 +28442,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -28491,9 +28491,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -28501,8 +28501,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -28520,10 +28520,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -28959,7 +28959,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -28967,7 +28967,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -29012,21 +29012,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -29036,12 +29036,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -29144,11 +29144,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -29266,6 +29266,6646 @@ function eventLog(harness2) { } } +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc2) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc2 && tagEntries.length > 0 && isNode(doc2.contents)) { + const tags = {}; + visit(doc2.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc2 || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc2, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc2)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc2, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc2)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: doc2, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc2, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc2, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc3, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc3, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc2, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc2); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc2, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc2, node.key, anchors); + const vc = getAliasCount(doc2, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc2, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc2.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc: doc2, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc: doc2 }) { + if (!doc2.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc2.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc: doc2, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc2.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc2, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc2.directives) { + const dir = doc2.directives.toString(doc2); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc2.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc2, options); + const { commentString } = ctx.options; + if (doc2.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc2.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc2.contents) { + if (isNode(doc2.contents)) { + if (doc2.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc2.contents.commentBefore) { + const cs = commentString(doc2.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc2.comment; + contentComment = doc2.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc2.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc2.contents, ctx)); + } + if (doc2.directives?.docEnd) { + if (doc2.comment) { + const cs = commentString(doc2.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc2.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc2 = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc2.directives, + options: doc2.options, + schema: doc2.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc2.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc2.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc2.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc2.comment = re.comment; + doc2.range = [offset, contentEnd, re.offset]; + return doc2; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc2, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc2.contents; + if (afterDoc) { + doc2.comment = doc2.comment ? `${doc2.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc2.directives.docStart || !dc) { + doc2.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc2.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc2.warnings.push(this.warnings[i]); + } else { + doc2.errors = this.errors; + doc2.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc2 = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc2.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc2, false); + if (this.doc) + yield this.doc; + this.doc = doc2; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc2 = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc2.range = [0, endOffset, endOffset]; + this.decorate(doc2, false); + yield doc2; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc2 = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc2.start.push(this.sourceToken); + this.stack.push(doc2); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc2) { + if (doc2.value) + return yield* this.lineEnd(doc2); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc2.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc2.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc2.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc2); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc2 of docs) { + doc2.errors.forEach(prettifyError(source, lineCounter)); + doc2.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc2 = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc2) + doc2 = _doc; + else if (doc2.options.logLevel !== "silent") { + doc2.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc2.errors.forEach(prettifyError(source, lineCounter)); + doc2.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc2; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc2 = parseDocument(src, options); + if (!doc2) + return null; + doc2.warnings.forEach((warning) => warn(doc2.options.logLevel, warning)); + if (doc2.errors.length > 0) { + if (doc2.options.logLevel !== "silent") + throw doc2.errors[0]; + else + doc2.errors = []; + } + return doc2.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -29702,7 +36342,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -29827,7 +36467,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -30738,8 +37378,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -31467,7 +38107,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -31696,7 +38336,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); diff --git a/host/js/events.md b/host/js/events.md index ca61775..929d0a0 100644 --- a/host/js/events.md +++ b/host/js/events.md @@ -42,7 +42,7 @@ Event emission updates the feed inside the same transaction. Notices become `sausage.notice` events. The host records each distinct notice once per facet load. -This task does not add Ultimate's build or supervisor startup events. +This task does not add Standing agent's build or supervisor startup events. ## Tests diff --git a/host/js/extensions-test-bundle.js b/host/js/extensions-test-bundle.js index fb57624..276e5e7 100644 --- a/host/js/extensions-test-bundle.js +++ b/host/js/extensions-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base, fragment) { let node = root2; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -20108,7 +20108,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28718,8 +28718,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -28825,8 +28825,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -28917,20 +28917,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -28966,9 +28966,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -28976,8 +28976,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -28995,10 +28995,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -29434,7 +29434,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -29442,7 +29442,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -29487,21 +29487,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -29511,12 +29511,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -29571,6 +29571,6646 @@ async function openStorage(path) { return SqliteStorage.open(database); } +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root2) { + const anchors = /* @__PURE__ */ new Set(); + visit(root2, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -30007,7 +36647,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -30132,7 +36772,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -31043,8 +37683,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -31246,11 +37886,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -31467,7 +38107,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -31696,7 +38336,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); diff --git a/host/js/extensions.ts b/host/js/extensions.ts index 493a087..00f85dc 100644 --- a/host/js/extensions.ts +++ b/host/js/extensions.ts @@ -1,5 +1,6 @@ // World extension snapshots, staged services, lifecycle, and last-good recovery. import * as durable from '@earendil-works/pi-durable'; +import * as yaml from 'yaml'; import * as tools from '@earendil-works/pi-durable/tools'; import * as ai from '@earendil-works/pi-ai'; import * as modelApi from '@earendil-works/pi-ai/models'; @@ -68,7 +69,7 @@ export async function git(cwd:string,...args:string[]) { return result.stdout.trim(); } export function registerModules() { - const modules = {'@earendil-works/sausage-events':events,'@earendil-works/pi-schema':schema,'@earendil-works/pi-durable':durable,'@earendil-works/pi-durable/tools':tools,'@earendil-works/pi-ai':ai,'@earendil-works/pi-ai/models':modelApi,'@earendil-works/chord':chord,'@earendil-works/chord/context':contextApi}; + const modules = {'yaml':yaml,'@earendil-works/sausage-events':events,'@earendil-works/pi-schema':schema,'@earendil-works/pi-durable':durable,'@earendil-works/pi-durable/tools':tools,'@earendil-works/pi-ai':ai,'@earendil-works/pi-ai/models':modelApi,'@earendil-works/chord':chord,'@earendil-works/chord/context':contextApi}; globalThis.__sausage = {modules}; ops.op_modules(Object.fromEntries(Object.entries(modules).map(([name,value])=>[name,Object.keys(value)]))); } @@ -209,7 +210,12 @@ export async function loadExtensions(harness:any, registry:any, storage:any, mod const rid = ops.op_watch([`${repo}/.git/refs/heads/main`,`${repo}/.git/packed-refs`,`${repo}/settings.json`]); await enqueue(); const pending = (async()=> {while(active){await ops.op_watch_next(rid);if(active)await enqueue();}})(); - return {reload:enqueue, state:()=>({...state}), async invoke(name:string,key:string,args:any,signal:AbortSignal,conversationId?:number) { + return {reload:enqueue, state:()=>({...state}), async standing() { + if (!providers.has('models') || !providers.has('subagents')) return undefined; + const {standing:name}=await providers.get('models').discover(repo); + const conversationId=await providers.get('subagents').standing(name,context); + return {name,conversationId}; + }, async invoke(name:string,key:string,args:any,signal:AbortSignal,conversationId?:number) { const facet = facets.find(f=>f.extension.name===name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error('Unknown user action'),{status:404}); diff --git a/host/js/foundation-test-bundle.js b/host/js/foundation-test-bundle.js index 920917a..ad8076f 100644 --- a/host/js/foundation-test-bundle.js +++ b/host/js/foundation-test-bundle.js @@ -20614,7 +20614,7 @@ async function openStorage(path2) { } // input.ts -async function serve(harness2, context, afterSubmit, api) { +async function serve(harness2, context, afterSubmit, api, defaultConversation) { const pending = /* @__PURE__ */ new Set(); const track2 = (work) => { const task = work.catch((error) => Deno.core.ops.op_output(`${String(error)} @@ -20637,8 +20637,9 @@ async function serve(harness2, context, afterSubmit, api) { track2(api.handle(input)); continue; } - const conversation = await harness2.conversation(input.conversation, context); - if (!conversation) throw new Error(`Unknown conversation: ${input.conversation}`); + const id = defaultConversation ? await defaultConversation() : input.conversation; + const conversation = await harness2.conversation(id, context); + if (!conversation) throw new Error(`Unknown conversation: ${id}`); const submission2 = await conversation.submit({ type: "input", content: input.content, diff --git a/host/js/foundation-test.ts b/host/js/foundation-test.ts index 52d2a68..69f8c3d 100644 --- a/host/js/foundation-test.ts +++ b/host/js/foundation-test.ts @@ -1,4 +1,4 @@ -// Ultimate's input-placement cases, scheduler hold, and the headless channel contract. +// Standing agent's input-placement cases, scheduler hold, and the headless channel contract. import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context'; import { createModels } from '@earendil-works/pi-ai/models'; import { fauxProvider, fauxAssistantMessage, fauxToolCall } from '@earendil-works/pi-ai/providers/faux'; diff --git a/host/js/goal-cases.ts b/host/js/goal-cases.ts index fc9f2e3..7a968ac 100644 --- a/host/js/goal-cases.ts +++ b/host/js/goal-cases.ts @@ -1,4 +1,4 @@ -/** The seven Ultimate goal cases use overlaid documents and the loaded server modules. */ +/** The seven Standing agent goal cases use overlaid documents and the loaded server modules. */ import type { ConversationId, GenerationHooks, Tx } from '@earendil-works/pi-durable' import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context' import { expect, it } from './goal-questions-test-support' @@ -6,7 +6,7 @@ const { reminderTask } = await import(`${globalThis.goalBase}/goal/reminder.ts`) const {default:goalExtension,act,actions,end,Goals,openGoal,start,TRIES} = await import(`${globalThis.goalBase}/goal/server.ts`) import type { Host } from './extensions.ts' -const ULTIMATE = 5 as ConversationId +const STANDING = 5 as ConversationId const screenshot = { type: 'image', data: 'aGk=', mimeType: 'image/png' } /** Like the harness's document overlay, a proxy at every level: structuredClone refuses it. */ @@ -18,17 +18,17 @@ const overlay = (value: T): T => }, }) -/** A transaction over overlaid documents and a few entries of @ultimate's conversation; @ultimate is conversation 5. */ +/** A transaction over overlaid documents and a few entries of @standing's conversation; @standing is conversation 5. */ function fakeTx( newer: { id: number; conversationId: number; kind?: string; model: object[] }[] = [], ) { const docs = new Map() const entries = [ ...newer, - { id: 30, conversationId: ULTIMATE, model: [{ role: 'user', content: 'no images' }] }, + { id: 30, conversationId: STANDING, model: [{ role: 'user', content: 'no images' }] }, { id: 20, - conversationId: ULTIMATE, + conversationId: STANDING, model: [{ role: 'toolResult', content: [{ type: 'text', text: 'shot' }, screenshot] }], }, { id: 10, conversationId: 9, model: [{ role: 'user', content: [screenshot] }] }, @@ -47,7 +47,7 @@ function fakeTx( if (!docs.has(key)) docs.set( key, - def.kind === 'ultimate.standing-agents' ? { ultimate: ULTIMATE } : def.initial(), + def.kind === 'standing.standing-agents' ? { '$standing': STANDING } : def.initial(), ) return overlay(docs.get(key)!) }, @@ -120,27 +120,27 @@ it('keeps one goal open at a time and ends it once', async () => { it('blocks a criterion after repeated failed tries and finishes with the outcome', async () => { const tx = fakeTx() - await expect(act(tx, ULTIMATE, { action: 'met', n: 1 }, 0)).rejects.toThrow('No hands-off goal') + await expect(act(tx, STANDING, { action: 'met', n: 1 }, 0)).rejects.toThrow('No hands-off goal') await start(tx, 'Goal', 0) - await act(tx, ULTIMATE, { action: 'criteria', criteria: ['Loads in 1s', 'Tests pass'] }, 0) - await expect(act(tx, ULTIMATE, { action: 'met', n: 3 }, 0)).rejects.toThrow('No criterion 3') - for (let i = 1; i < TRIES; i++) await act(tx, ULTIMATE, { action: 'failed', n: 1 }, 0) + await act(tx, STANDING, { action: 'criteria', criteria: ['Loads in 1s', 'Tests pass'] }, 0) + await expect(act(tx, STANDING, { action: 'met', n: 3 }, 0)).rejects.toThrow('No criterion 3') + for (let i = 1; i < TRIES; i++) await act(tx, STANDING, { action: 'failed', n: 1 }, 0) expect((await openGoal(tx))!.criteria[0]).toMatchObject({ status: 'open', tries: TRIES - 1 }) - const last = await act(tx, ULTIMATE, { action: 'failed', n: 1 }, 0) + const last = await act(tx, STANDING, { action: 'failed', n: 1 }, 0) expect(last.answer).toContain('blocked') expect((await openGoal(tx))!.criteria[0].status).toBe('blocked') // Rewording keeps what was learned about an unchanged criterion. - await act(tx, ULTIMATE, { action: 'criteria', criteria: ['Loads in 1s', 'Lint passes'] }, 0) + await act(tx, STANDING, { action: 'criteria', criteria: ['Loads in 1s', 'Lint passes'] }, 0) expect((await openGoal(tx))!.criteria.map((item) => item.status)).toEqual(['blocked', 'open']) - await expect(act(tx, ULTIMATE, { action: 'finish', summary: 'x' }, 0)).rejects.toThrow('outcome') + await expect(act(tx, STANDING, { action: 'finish', summary: 'x' }, 0)).rejects.toThrow('outcome') const done = await act( tx, - ULTIMATE, + STANDING, { action: 'finish', outcome: 'blocked', summary: 'Stuck' }, 4, ) expect(done.ended).toMatchObject({ - ended: { by: 'ultimate', outcome: 'blocked', summary: 'Stuck' }, + ended: { by: 'standing', outcome: 'blocked', summary: 'Stuck' }, }) expect(await openGoal(tx)).toBeUndefined() }) @@ -149,11 +149,11 @@ it('records decisions with the screenshots of its own conversation only', async const tx = fakeTx() await start(tx, 'Goal', 0) await expect( - act(tx, ULTIMATE, { action: 'decide', question: 'Go?', picked: 'Yes' }, 0), + act(tx, STANDING, { action: 'decide', question: 'Go?', picked: 'Yes' }, 0), ).rejects.toThrow('reason') await act( tx, - ULTIMATE, + STANDING, { action: 'decide', question: 'Approve?', @@ -165,7 +165,7 @@ it('records decisions with the screenshots of its own conversation only', async 1, ) await expect( - act(tx, ULTIMATE, { action: 'decide', question: 'q', picked: 'p', reason: 'r', images: 10 }, 2), + act(tx, STANDING, { action: 'decide', question: 'q', picked: 'p', reason: 'r', images: 10 }, 2), ).rejects.toThrow('has no images') expect((await openGoal(tx))!.decisions).toEqual([ { at: 1, question: 'Approve?', picked: 'Yes', reason: 'Meets 1', conversation: 7, images: 20 }, @@ -173,17 +173,17 @@ it('records decisions with the screenshots of its own conversation only', async }) it('never takes an earlier turn\'s screenshot for images: "latest"', async () => { - const tx = fakeTx([{ id: 40, kind: 'pi.user', conversationId: ULTIMATE, model: [] }]) + const tx = fakeTx([{ id: 40, kind: 'pi.user', conversationId: STANDING, model: [] }]) await start(tx, 'Goal', 0) const decide = { action: 'decide', question: 'q', picked: 'p', reason: 'r' } as const - await expect(act(tx, ULTIMATE, { ...decide, images: 'latest' }, 1)).rejects.toThrow( + await expect(act(tx, STANDING, { ...decide, images: 'latest' }, 1)).rejects.toThrow( 'no images in this turn', ) - await act(tx, ULTIMATE, { ...decide, images: 20 }, 2) + await act(tx, STANDING, { ...decide, images: 20 }, 2) expect((await openGoal(tx))!.decisions).toMatchObject([{ images: 20 }]) }) -it("notes the open goal on @ultimate's runs only, and lets only @ultimate keep it", async () => { +it("notes the open goal on @standing's runs only, and lets only @standing keep it", async () => { const tx = fakeTx() const extension = goalExtension({ doc: () => undefined, @@ -193,10 +193,10 @@ it("notes the open goal on @ultimate's runs only, and lets only @ultimate keep i const hooks = extension.hooks![0].handlers as GenerationHooks const before = (conversationId: number, kind = 'pi.user') => hooks.beforeInput({ kind }, { tx, conversationId } as never, BACKGROUND_CONTEXT) - expect(await before(ULTIMATE)).toBeUndefined() + expect(await before(STANDING)).toBeUndefined() await start(tx, 'Make it fast', 0) expect(await before(9)).toBeUndefined() - const note = (await before(ULTIMATE))!.entries![0] + const note = (await before(STANDING))!.entries![0] expect(note.kind).toBe('goal.note') expect(note.model![0].content).toContain( 'Hands-off goal 1, granted by the user, who is away: Make it fast', @@ -209,19 +209,19 @@ it("notes the open goal on @ultimate's runs only, and lets only @ultimate keep i { conversationId, commit: (fn: (tx: Tx) => unknown) => fn(tx) } as never, undefined as never, ) - await expect(run(9, { action: 'met', n: 1 })).rejects.toThrow('Only @ultimate') - expect(await run(ULTIMATE, { action: 'criteria', criteria: ['Fast'] })).toEqual({ + await expect(run(9, { action: 'met', n: 1 })).rejects.toThrow('Only the standing agent') + expect(await run(STANDING, { action: 'criteria', criteria: ['Fast'] })).toEqual({ content: [{ type: 'text', text: 'Goal 1 has 1 criteria.' }], }) expect((await tx.doc(Goals, 1 as ConversationId)).goals[0].criteria).toHaveLength(1) // Finishing ends the goal and creates the report's delivery in the same commit; the note stops. - await run(ULTIMATE, { action: 'finish', outcome: 'met', summary: 'Done' }) + await run(STANDING, { action: 'finish', outcome: 'met', summary: 'Done' }) expect(tx.tasks).toEqual([ - { name: 'goal.deliver', input: expect.objectContaining({ to: ULTIMATE, kind: 'goal.report' }) }, + { name: 'goal.deliver', input: expect.objectContaining({ to: STANDING, kind: 'goal.report' }) }, { name: 'goal.reminder', input: { goal: 1 } }, ]) - expect(await before(ULTIMATE)).toBeUndefined() + expect(await before(STANDING)).toBeUndefined() }) it('keeps a reminder while the goal is open: paused while waiting on the user, gone once ended', async () => { @@ -232,7 +232,7 @@ it('keeps a reminder while the goal is open: paused while waiting on the user, g const run = (args: object) => tool.execute( args as never, - { conversationId: ULTIMATE, commit: (fn: (tx: Tx) => unknown) => fn(tx) } as never, + { conversationId: STANDING, commit: (fn: (tx: Tx) => unknown) => fn(tx) } as never, undefined as never, ) await actions.start({ text: 'Make it fast' }, { host } as never) @@ -240,7 +240,7 @@ it('keeps a reminder while the goal is open: paused while waiting on the user, g // its key instead of making a second one, and pauses it. await service.create({ name: 'Goal reminder · goal 1', - subscribers: ['@ultimate'], + subscribers: ['@standing'], key: 'goal.reminder:1', }) ;(await openGoal(tx))!.waiting = { reason: 'Which account?', at: 0 } @@ -249,7 +249,7 @@ it('keeps a reminder while the goal is open: paused while waiting on the user, g { id: 'A1', name: 'Goal reminder · goal 1', - subscribers: ['@ultimate'], + subscribers: ['@standing'], key: 'goal.reminder:1', enabled: false, }, @@ -261,10 +261,10 @@ it('keeps a reminder while the goal is open: paused while waiting on the user, g // The user renamed it: it stays linked by its id. ledger.get('A1')!.name = 'Night check' - // Its fire tells @ultimate what to check; other inputs do not. + // Its fire tells @standing what to check; other inputs do not. const hooks = extension.hooks![0].handlers as GenerationHooks const note = async (input: object) => - (await hooks.beforeInput(input as never, { tx, conversationId: ULTIMATE }, BACKGROUND_CONTEXT))! + (await hooks.beforeInput(input as never, { tx, conversationId: STANDING }, BACKGROUND_CONTEXT))! .entries![0].model![0].content as string expect(await note({ kind: 'automations.fired', data: { id: 'A1' } })).toContain( 'This is the goal reminder', @@ -315,7 +315,7 @@ it('grants nothing through a start card still queued after the user ended its go expect( await hooks.beforeInput( { kind: 'goal.started' }, - { tx, conversationId: ULTIMATE }, + { tx, conversationId: STANDING }, BACKGROUND_CONTEXT, ), ).toBeUndefined() diff --git a/host/js/goal-questions-fixture.ts b/host/js/goal-questions-fixture.ts index 5229ceb..30c5a5e 100644 --- a/host/js/goal-questions-fixture.ts +++ b/host/js/goal-questions-fixture.ts @@ -30,8 +30,8 @@ export async function fixture(clock: any = {}) { const settled=async()=>{await until(async()=>(await harness.commit((tx:any)=>tx.scanTasks({},1000),context)).items.every((t:any)=>t.state.status==='terminal'));await harness.waitForIdle(context)} const entries=async(id:number)=>(await harness.commit((tx:any)=>tx.scanEntries({conversationId:id},1000),context)).items.toSorted((a:any,b:any)=>a.id-b.id) const type=async(id:number,content:string)=>{const c=await harness.conversation(id,context);await(await c.submit({type:'input',content},context)).wait(context)} - const ultimate=async()=>{const c=await harness.createConversation({ownership:{kind:'ownerless'}},context);await c.configure({model:{provider:'faux',modelId:'faux-1'}},context);await harness.commit(async(tx:any)=>{(await tx.doc(Standing,root.id)).ultimate=c.id},context);return c.id} + const standing=async()=>{const c=await harness.createConversation({ownership:{kind:'ownerless'}},context);await c.configure({model:{provider:'faux',modelId:'faux-1'}},context);await harness.commit(async(tx:any)=>{(await tx.doc(Standing,root.id))['$standing']=c.id},context);return c.id} const ask=async(id:number,args:any)=>{await type(id,`SEND ${JSON.stringify({to:'user',...args})}`);await settled();const result=(await entries(id)).findLast((e:any)=>e.kind==='pi.tool-result')?.model?.[0];return {error:result?.isError?result.content.map((p:any)=>p.text).join(''):undefined,message:(await log()).messages.findLast((m:any)=>m.from===id&&m.to==='user')}} const action=(conversationId?:number)=>({host:globalThis.testHost,conversationId,signal:new AbortController().signal}) - return {base,faux,loader,host:globalThis.testHost,opened:{harness,root,close:async()=>{await loader.close();await harness.close(context);await storage.close()}},ultimate,type,ask,answer:(args:any)=>question.actions.answer(args,action()),dismiss:(messageId:number)=>question.actions.dismiss({messageId},action()),log,entries,observed,settled,hear:(fn:any)=>heard=fn} + return {base,faux,loader,host:globalThis.testHost,opened:{harness,root,close:async()=>{await loader.close();await harness.close(context);await storage.close()}},standing,type,ask,answer:(args:any)=>question.actions.answer(args,action()),dismiss:(messageId:number)=>question.actions.dismiss({messageId},action()),log,entries,observed,settled,hear:(fn:any)=>heard=fn} } diff --git a/host/js/goal-questions-test-bundle.js b/host/js/goal-questions-test-bundle.js index c9a1fa4..ecc8617 100644 --- a/host/js/goal-questions-test-bundle.js +++ b/host/js/goal-questions-test-bundle.js @@ -41,10 +41,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge )); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -106,8 +106,8 @@ var init_memory = __esm({ }); // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -359,7 +359,7 @@ var init_event_stream = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -376,7 +376,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1243,11 +1243,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1259,14 +1259,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -2294,8 +2294,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -3375,11 +3375,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3393,8 +3393,8 @@ function map(value2, options = {}) { function bytes(options = {}) { return { type: "bytes", ...options }; } -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3421,8 +3421,8 @@ var init_builders = __esm({ "node_modules/@earendil-works/pi-schema/dist/builders.js"() { Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; } @@ -3490,8 +3490,8 @@ var init_resolver = __esm({ if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3567,10 +3567,10 @@ var init_resolver = __esm({ for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3580,12 +3580,12 @@ var init_resolver = __esm({ } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root, base, fragment) { let node = root; @@ -3647,17 +3647,17 @@ var init_shared = __esm({ }); // node_modules/@earendil-works/pi-schema/dist/coerce.js -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next2 = map2(items[i], i); + const next2 = map3(items[i], i); if (next2 === items[i]) continue; out ??= items.slice(); @@ -3751,11 +3751,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -3839,9 +3839,9 @@ var init_coerce = __esm({ * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3903,26 +3903,26 @@ var init_coerce = __esm({ // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next2) => { + const set2 = (key, next2) => { if (next2 === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3937,7 +3937,7 @@ var init_coerce = __esm({ delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3946,10 +3946,10 @@ var init_coerce = __esm({ if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -4055,8 +4055,8 @@ var init_coerce = __esm({ return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -4069,7 +4069,7 @@ var init_coerce = __esm({ if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -4079,11 +4079,11 @@ var init_coerce = __esm({ let matched = Object.hasOwn(properties, key); if (matched) next2 = this.convert(properties[key], base, next2); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next2 = this.convert(schema, base, next2); + next2 = this.convert(schema4, base, next2); } if (!matched && additional !== void 0) next2 = this.convert(additional, base, next2); @@ -4097,19 +4097,19 @@ var init_coerce = __esm({ // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next2 = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next2 = this.coerceTypes(next2, member, b); - if (Array.isArray(schema.anyOf)) - next2 = this.coerceUnion(next2, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next2 = this.coerceUnion(next2, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next2 = this.coerceUnion(next2, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next2 = this.coerceUnion(next2, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next2, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -4121,9 +4121,9 @@ var init_coerce = __esm({ } } if (types.includes("object") && isPlainObject(next2)) - next2 = this.coerceProperties(next2, schema, b); + next2 = this.coerceProperties(next2, schema4, b); if (types.includes("array") && Array.isArray(next2)) - next2 = this.coerceItems(next2, schema, b); + next2 = this.coerceItems(next2, schema4, b); return next2; } coerceUnion(value2, branches, base) { @@ -4137,12 +4137,12 @@ var init_coerce = __esm({ } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next2) => { + const set2 = (key, next2) => { if (next2 === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -4150,7 +4150,7 @@ var init_coerce = __esm({ }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -4158,16 +4158,16 @@ var init_coerce = __esm({ if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } @@ -4474,9 +4474,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4818,9 +4818,9 @@ var init_compiler = __esm({ scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4886,9 +4886,9 @@ var init_compiler = __esm({ parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4899,7 +4899,7 @@ var init_compiler = __esm({ const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5313,9 +5313,9 @@ var init_explain = __esm({ * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5642,22 +5642,22 @@ var init_explain = __esm({ }); // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } var NO_OPTIONS, Validator, CoercingValidator; @@ -5673,9 +5673,9 @@ var init_validator = __esm({ schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5821,34 +5821,34 @@ function hash64(text) { function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5865,12 +5865,12 @@ function cloneData(value2) { copy2[key] = cloneData(item); return copy2; } -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5879,21 +5879,21 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5901,42 +5901,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5944,7 +5944,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5953,16 +5953,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5975,28 +5975,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -6113,7 +6113,7 @@ var init_schema = __esm({ "node_modules/@earendil-works/chord/dist/schema.js"() { init_dist2(); init_errors(); - asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; + asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; validators = /* @__PURE__ */ new WeakMap(); isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); @@ -6134,7 +6134,7 @@ var init_schema = __esm({ "minProperties", "maxProperties" ]; - typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; + typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -6162,7 +6162,7 @@ var init_schema = __esm({ "writeOnly", "deprecated" ]); - withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); + withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); } }); @@ -6229,8 +6229,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9870,15 +9870,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -9964,10 +9964,10 @@ var init_cell = __esm({ validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9984,11 +9984,11 @@ var init_cell = __esm({ * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial2, guard, options) { + constructor(key, schema4, initial2, guard, options) { super(key, options); if (initial2 !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial2.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial2.value); + this.schema = schema4; this.#tracker = track({ v: initial2?.value ?? null }); this.#guard = guard; this.#initialized = initial2 !== void 0; @@ -10052,8 +10052,8 @@ var init_cell = __esm({ * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -10250,18 +10250,18 @@ function notifyStatus(listeners, status, error, report2) { }); } function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -10627,8 +10627,8 @@ var init_object = __esm({ const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -11099,15 +11099,15 @@ var init_object = __esm({ } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11368,8 +11368,8 @@ var init_object = __esm({ throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11480,16 +11480,16 @@ var init_object = __esm({ this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11518,13 +11518,13 @@ var init_object = __esm({ return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial2, options = {}) { + state(name, schema4, initial2, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11533,7 +11533,7 @@ var init_object = __esm({ const init = isStateInit(initial2) ? initial2.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial2 } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial2 } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11541,7 +11541,7 @@ var init_object = __esm({ this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11645,15 +11645,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -12027,17 +12027,17 @@ var init_reload = __esm({ for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -12209,11 +12209,11 @@ var init_reload = __esm({ } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -14155,10 +14155,10 @@ var init_remote = __esm({ removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -14185,12 +14185,12 @@ var init_remote = __esm({ view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14469,8 +14469,8 @@ var init_remote = __esm({ if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14970,11 +14970,11 @@ var init_host = __esm({ * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -15222,15 +15222,15 @@ var init_host = __esm({ table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry.name, set); + let set2 = this.#subscribers.get(registry.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16807,19 +16807,19 @@ var init_cached_storage = __esm({ }); // node_modules/@earendil-works/pi-durable/dist/session/conversation-tails.js -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17750,14 +17750,14 @@ var init_transaction = __esm({ this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -18148,8 +18148,8 @@ var init_writer = __esm({ } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -18182,8 +18182,8 @@ var init_writer = __esm({ failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -18201,7 +18201,7 @@ var init_writer = __esm({ try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -19171,7 +19171,7 @@ var init_session = __esm({ writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -19181,15 +19181,15 @@ var init_session = __esm({ * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -19200,7 +19200,7 @@ var init_session = __esm({ * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -19213,7 +19213,7 @@ var init_session = __esm({ continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -19282,7 +19282,7 @@ var init_session = __esm({ const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -19290,7 +19290,7 @@ var init_session = __esm({ hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -19345,7 +19345,7 @@ var init_session = __esm({ * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -19373,9 +19373,9 @@ var init_session = __esm({ const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19879,7 +19879,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19887,27 +19887,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20560,7 +20560,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -20568,7 +20568,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } var SCAN_PAGE_SIZE2, EXCLUDED_STOP_REASONS, MISSING_RESULT_TEXT, deeplyFrozen; @@ -21026,21 +21026,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -21082,14 +21082,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -21118,9 +21118,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -21349,12 +21349,12 @@ var init_util = __esm({ if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -21368,16 +21368,16 @@ var init_util = __esm({ return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -21454,20 +21454,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -25067,13 +25067,13 @@ var init_formats = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/utils/validation.js -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -25591,18 +25591,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation return { ...rest, ...value2, output: bounded.content, diagnostics: [...rest.diagnostics ?? [], ...harness] }; } function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25780,7 +25780,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25794,7 +25794,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -29005,16 +29005,16 @@ var init_memory2 = __esm({ seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -29022,14 +29022,14 @@ var init_memory2 = __esm({ this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -29067,7 +29067,7 @@ var init_memory2 = __esm({ } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -29085,7 +29085,7 @@ var init_memory2 = __esm({ case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -29155,9 +29155,9 @@ var init_memory2 = __esm({ break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -29500,16 +29500,16 @@ var init_memory2 = __esm({ throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions2, seq) { + applyDocumentActions(actions2, seq2) { for (const [id, action] of actions2) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -29527,14 +29527,14 @@ var init_memory2 = __esm({ insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -29740,8 +29740,8 @@ var init_schema3 = __esm({ }); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -29845,8 +29845,8 @@ function createSqliteMigrations(schema) { { version: 2, statements: sleepingStatus } ]; } -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } var SQLITE_MIGRATIONS, CURRENT_SQLITE_SCHEMA_VERSION; var init_migrations2 = __esm({ @@ -29955,20 +29955,20 @@ var init_storage = __esm({ closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -30004,9 +30004,9 @@ var init_storage = __esm({ refused = { error }; break; } - const seq = seqFromNumber(next2++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next2++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -30014,8 +30014,8 @@ var init_storage = __esm({ } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -30033,10 +30033,10 @@ var init_storage = __esm({ await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -30472,7 +30472,7 @@ var init_storage = __esm({ LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -30480,7 +30480,7 @@ var init_storage = __esm({ break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -30525,21 +30525,21 @@ var init_storage = __esm({ } } } - async applyDocumentActions(executor, actions2, seq) { + async applyDocumentActions(executor, actions2, seq2) { for (const [id, action] of actions2) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -30549,12 +30549,12 @@ var init_storage = __esm({ await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -30624,6 +30624,7212 @@ var init_sqlite3 = __esm({ } }); +// node_modules/yaml/browser/dist/nodes/identity.js +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var ALIAS, DOC, MAP, PAIR, SCALAR, SEQ, NODE_TYPE, isAlias, isDocument, isMap, isPair, isScalar, isSeq, hasAnchor; +var init_identity2 = __esm({ + "node_modules/yaml/browser/dist/nodes/identity.js"() { + ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); + DOC = /* @__PURE__ */ Symbol.for("yaml.document"); + MAP = /* @__PURE__ */ Symbol.for("yaml.map"); + PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); + SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); + SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); + NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); + isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; + isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; + isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; + isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; + isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; + isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; + hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + } +}); + +// node_modules/yaml/browser/dist/visit.js +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} +var BREAK, SKIP, REMOVE; +var init_visit = __esm({ + "node_modules/yaml/browser/dist/visit.js"() { + init_identity2(); + BREAK = /* @__PURE__ */ Symbol("break visit"); + SKIP = /* @__PURE__ */ Symbol("skip children"); + REMOVE = /* @__PURE__ */ Symbol("remove node"); + visit.BREAK = BREAK; + visit.SKIP = SKIP; + visit.REMOVE = REMOVE; + visitAsync.BREAK = BREAK; + visitAsync.SKIP = SKIP; + visitAsync.REMOVE = REMOVE; + } +}); + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars, escapeTagName, Directives; +var init_directives = __esm({ + "node_modules/yaml/browser/dist/doc/directives.js"() { + init_identity2(); + init_visit(); + escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" + }; + escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); + Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } + }; + Directives.defaultYaml = { explicit: false, version: "1.2" }; + Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + } +}); + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} +var init_anchors = __esm({ + "node_modules/yaml/browser/dist/doc/anchors.js"() { + init_identity2(); + init_visit(); + } +}); + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} +var init_applyReviver = __esm({ + "node_modules/yaml/browser/dist/doc/applyReviver.js"() { + } +}); + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} +var init_toJS = __esm({ + "node_modules/yaml/browser/dist/nodes/toJS.js"() { + init_identity2(); + } +}); + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase; +var init_Node = __esm({ + "node_modules/yaml/browser/dist/nodes/Node.js"() { + init_applyReviver(); + init_identity2(); + init_toJS(); + NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + }; + } +}); + +// node_modules/yaml/browser/dist/nodes/Alias.js +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} +var Alias; +var init_Alias = __esm({ + "node_modules/yaml/browser/dist/nodes/Alias.js"() { + init_anchors(); + init_visit(); + init_identity2(); + init_Node(); + init_toJS(); + Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } + }; + } +}); + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue, Scalar; +var init_Scalar = __esm({ + "node_modules/yaml/browser/dist/nodes/Scalar.js"() { + init_identity2(); + init_Node(); + init_toJS(); + isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; + Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } + }; + Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; + Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; + Scalar.PLAIN = "PLAIN"; + Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; + Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + } +}); + +// node_modules/yaml/browser/dist/doc/createNode.js +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} +var defaultTagPrefix; +var init_createNode = __esm({ + "node_modules/yaml/browser/dist/doc/createNode.js"() { + init_Alias(); + init_identity2(); + init_Scalar(); + defaultTagPrefix = "tag:yaml.org,2002:"; + } +}); + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath, Collection; +var init_Collection = __esm({ + "node_modules/yaml/browser/dist/nodes/Collection.js"() { + init_createNode(); + init_identity2(); + init_Node(); + isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; + Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it2) => isNode(it2) || isPair(it2) ? it2.clone(schema4) : it2); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + }; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var stringifyComment, lineComment; +var init_stringifyComment = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyComment.js"() { + stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); + lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + } +}); + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end2 = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end2 = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end2 = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end2 = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next2 = text[i + 1]; + if (next2 && next2 !== " " && next2 !== "\n" && next2 !== " ") + split = i; + } + if (i >= end2) { + if (split) { + folds.push(split); + end2 = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end2 = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end3 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end3)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end3)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end2 = i; + let start2 = i + 1; + let ch = text[start2]; + while (ch === " " || ch === " ") { + if (i < start2 + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end2 = i; + start2 = i + 1; + ch = text[start2]; + } + } + return end2; +} +var FOLD_FLOW, FOLD_BLOCK, FOLD_QUOTED; +var init_foldFlowLines = __esm({ + "node_modules/yaml/browser/dist/stringify/foldFlowLines.js"() { + FOLD_FLOW = "flow"; + FOLD_BLOCK = "block"; + FOLD_QUOTED = "quoted"; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start2 = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start2 > limit) + return true; + start2 = i + 1; + if (strLen - start2 <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start2 = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start2, i) + "\\ "; + i += 1; + start2 = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start2, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start2 = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start2, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start2 = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start2 ? str2 + json.slice(start2) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +function blockString({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + const { blockQuote, commentString, lineWidth } = ctx.options; + if (!blockQuote || /\n[\t ]+$/.test(value2)) { + return quotedString(value2, ctx); + } + const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value2) ? " " : ""); + const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value2, lineWidth, indent.length); + if (!value2) + return literal ? "|\n" : ">\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end2 = value2.substring(endStart); + const endNlPos = end2.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end2 || endNlPos !== end2.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end2) { + value2 = value2.slice(0, -end2.length); + if (end2[end2.length - 1] === "\n") + end2 = end2.slice(0, -1); + end2 = end2.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start2 = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start2) { + value2 = value2.substring(start2.length); + start2 = start2.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start2}${foldedValue}${end2}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start2}${value2}${end2}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} +var getFoldOptions, containsDocumentMarker, blockEndNewlines; +var init_stringifyString = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyString.js"() { + init_Scalar(); + init_foldFlowLines(); + getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth + }); + containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); + try { + blockEndNewlines = new RegExp("(^|(? t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} +var init_stringify = __esm({ + "node_modules/yaml/browser/dist/stringify/stringify.js"() { + init_anchors(); + init_identity2(); + init_stringifyComment(); + init_stringifyString(); + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} +var init_stringifyPair = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyPair.js"() { + init_identity2(); + init_Scalar(); + init_stringify(); + init_stringifyComment(); + } +}); + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} +var init_log = __esm({ + "node_modules/yaml/browser/dist/log.js"() { + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it2 of source.items) + mergeValue(ctx, map3, it2); + else if (Array.isArray(source)) + for (const it2 of source) + mergeValue(ctx, map3, it2); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} +var MERGE_KEY, merge3, isMergeKey; +var init_merge = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js"() { + init_identity2(); + init_Scalar(); + MERGE_KEY = "<<"; + merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY + }; + isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); + } +}); + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} +var init_addPairToJSMap = __esm({ + "node_modules/yaml/browser/dist/nodes/addPairToJSMap.js"() { + init_log(); + init_merge(); + init_stringify(); + init_identity2(); + init_toJS(); + } +}); + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair; +var init_Pair = __esm({ + "node_modules/yaml/browser/dist/nodes/Pair.js"() { + init_createNode(); + init_stringifyPair(); + init_addPairToJSMap(); + init_identity2(); + Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } + }; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start: start2, end: end2 } = flowChars; + if (lines2.length === 0) { + return start2 + end2; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start2; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end2}`; + } else { + return `${start2}${fcPadding}${lines2.join(" ")}${fcPadding}${end2}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} +var init_stringifyCollection = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyCollection.js"() { + init_identity2(); + init_stringify(); + init_stringifyComment(); + } +}); + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it2 of items) { + if (isPair(it2)) { + if (it2.key === key || it2.key === k) + return it2; + if (isScalar(it2.key) && it2.key.value === k) + return it2; + } + } + return void 0; +} +var YAMLMap; +var init_YAMLMap = __esm({ + "node_modules/yaml/browser/dist/nodes/YAMLMap.js"() { + init_stringifyCollection(); + init_addPairToJSMap(); + init_Collection(); + init_identity2(); + init_Pair(); + init_Scalar(); + YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it2 = findPair(this.items, key); + if (!it2) + return false; + const del = this.items.splice(this.items.indexOf(it2), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it2 = findPair(this.items, key); + const node = it2?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2; +var init_map = __esm({ + "node_modules/yaml/browser/dist/schema/common/map.js"() { + init_identity2(); + init_YAMLMap(); + map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) + }; + } +}); + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} +var YAMLSeq; +var init_YAMLSeq = __esm({ + "node_modules/yaml/browser/dist/nodes/YAMLSeq.js"() { + init_createNode(); + init_stringifyCollection(); + init_Collection(); + init_identity2(); + init_Scalar(); + init_toJS(); + YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it2 = this.items[idx]; + return !keepScalar && isScalar(it2) ? it2.value : it2; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it2 of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it2 : String(i++); + it2 = replacer.call(obj2, key, it2); + } + seq2.items.push(createNode2(it2, void 0, ctx)); + } + } + return seq2; + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq; +var init_seq = __esm({ + "node_modules/yaml/browser/dist/schema/common/seq.js"() { + init_identity2(); + init_YAMLSeq(); + seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) + }; + } +}); + +// node_modules/yaml/browser/dist/schema/common/string.js +var string; +var init_string = __esm({ + "node_modules/yaml/browser/dist/schema/common/string.js"() { + init_stringifyString(); + string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag; +var init_null = __esm({ + "node_modules/yaml/browser/dist/schema/common/null.js"() { + init_Scalar(); + nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr + }; + } +}); + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag; +var init_bool = __esm({ + "node_modules/yaml/browser/dist/schema/core/bool.js"() { + init_Scalar(); + boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } + }; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} +var init_stringifyNumber = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyNumber.js"() { + } +}); + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN, floatExp, float; +var init_float = __esm({ + "node_modules/yaml/browser/dist/schema/core/float.js"() { + init_Scalar(); + init_stringifyNumber(); + floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber + }; + floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } + }; + float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber + }; + } +}); + +// node_modules/yaml/browser/dist/schema/core/int.js +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intIdentify, intResolve, intOct, int2, intHex; +var init_int = __esm({ + "node_modules/yaml/browser/dist/schema/core/int.js"() { + init_stringifyNumber(); + intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); + intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); + intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") + }; + int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber + }; + intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") + }; + } +}); + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema; +var init_schema4 = __esm({ + "node_modules/yaml/browser/dist/schema/core/schema.js"() { + init_map(); + init_null(); + init_seq(); + init_string(); + init_bool(); + init_float(); + init_int(); + schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float + ]; + } +}); + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON, jsonScalars, jsonError, schema2; +var init_schema5 = __esm({ + "node_modules/yaml/browser/dist/schema/json/schema.js"() { + init_Scalar(); + init_map(); + init_seq(); + stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); + jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } + ]; + jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } + }; + schema2 = [map2, seq].concat(jsonScalars, jsonError); + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary; +var init_binary = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js"() { + init_Scalar(); + init_stringifyString(); + binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it2 of iterable) { + if (typeof replacer === "function") + it2 = replacer.call(iterable, String(i++), it2); + let key, value2; + if (Array.isArray(it2)) { + if (it2.length === 2) { + key = it2[0]; + value2 = it2[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it2}`); + } else if (it2 && it2 instanceof Object) { + const keys = Object.keys(it2); + if (keys.length === 1) { + key = keys[0]; + value2 = it2[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it2; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs; +var init_pairs = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js"() { + init_identity2(); + init_Pair(); + init_Scalar(); + init_YAMLSeq(); + pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap, omap; +var init_omap = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js"() { + init_identity2(); + init_toJS(); + init_YAMLMap(); + init_YAMLSeq(); + init_pairs(); + YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } + }; + YAMLOMap.tag = "tag:yaml.org,2002:omap"; + omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag, falseTag; +var init_bool2 = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js"() { + init_Scalar(); + trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify + }; + falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2, floatExp2, float2; +var init_float2 = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/float.js"() { + init_Scalar(); + init_stringifyNumber(); + floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber + }; + floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } + }; + float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intIdentify3, intBin, intOct2, int3, intHex2; +var init_int2 = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/int.js"() { + init_stringifyNumber(); + intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); + intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") + }; + intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") + }; + int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber + }; + intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet, set; +var init_set = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/set.js"() { + init_identity2(); + init_Pair(); + init_YAMLMap(); + YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } + }; + YAMLSet.tag = "tag:yaml.org,2002:set"; + set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime, floatTime, timestamp; +var init_timestamp = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js"() { + init_stringifyNumber(); + intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal + }; + floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal + }; + timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" + }; + } +}); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3; +var init_schema6 = __esm({ + "node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js"() { + init_map(); + init_null(); + init_seq(); + init_string(); + init_binary(); + init_bool2(); + init_float2(); + init_int2(); + init_merge(); + init_omap(); + init_pairs(); + init_set(); + init_timestamp(); + schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp + ]; + } +}); + +// node_modules/yaml/browser/dist/schema/tags.js +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} +var schemas, tagsByName, coreKnownTags; +var init_tags = __esm({ + "node_modules/yaml/browser/dist/schema/tags.js"() { + init_map(); + init_null(); + init_seq(); + init_string(); + init_bool(); + init_float(); + init_int(); + init_schema4(); + init_schema5(); + init_binary(); + init_merge(); + init_omap(); + init_pairs(); + init_schema6(); + init_set(); + init_timestamp(); + schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] + ]); + tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp + }; + coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp + }; + } +}); + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey, Schema; +var init_Schema = __esm({ + "node_modules/yaml/browser/dist/schema/Schema.js"() { + init_identity2(); + init_map(); + init_seq(); + init_string(); + init_tags(); + sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } + }; + } +}); + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} +var init_stringifyDocument = __esm({ + "node_modules/yaml/browser/dist/stringify/stringifyDocument.js"() { + init_identity2(); + init_stringify(); + init_stringifyComment(); + } +}); + +// node_modules/yaml/browser/dist/doc/Document.js +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} +var Document; +var init_Document = __esm({ + "node_modules/yaml/browser/dist/doc/Document.js"() { + init_Alias(); + init_Collection(); + init_identity2(); + init_Pair(); + init_toJS(); + init_Schema(); + init_stringifyDocument(); + init_anchors(); + init_applyReviver(); + init_createNode(); + init_directives(); + Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } + }; + } +}); + +// node_modules/yaml/browser/dist/errors.js +var YAMLError, YAMLParseError, YAMLWarning, prettifyError; +var init_errors3 = __esm({ + "node_modules/yaml/browser/dist/errors.js"() { + YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } + }; + YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } + }; + YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } + }; + prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end2 = error.linePos[1]; + if (end2?.line === line && end2.col > col) { + count = Math.max(1, Math.min(end2.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } + }; + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next: next2, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start2 = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next2?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start2 ?? (start2 = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start2 ?? (start2 = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end2 = last ? last.offset + last.source.length : offset; + if (reqSpace && next2 && next2.type !== "space" && next2.type !== "newline" && next2.type !== "comma" && (next2.type !== "scalar" || next2.source !== "")) { + onError(next2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next2?.type === "block-map" || next2?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end: end2, + start: start2 ?? end2 + }; +} +var init_resolve_props = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-props.js"() { + } +}); + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it2 of key.items) { + for (const st of it2.start) + if (st.type === "newline") + return true; + if (it2.sep) { + for (const st of it2.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it2.key) || containsNewline(it2.value)) + return true; + } + return false; + default: + return true; + } +} +var init_util_contains_newline = __esm({ + "node_modules/yaml/browser/dist/compose/util-contains-newline.js"() { + } +}); + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end2 = fc.end[0]; + if (end2.indent === indent && (end2.source === "]" || end2.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end2, "BAD_INDENT", msg, true); + } + } +} +var init_util_flow_indent_check = __esm({ + "node_modules/yaml/browser/dist/compose/util-flow-indent-check.js"() { + init_util_contains_newline(); + } +}); + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} +var init_util_map_includes = __esm({ + "node_modules/yaml/browser/dist/compose/util-map-includes.js"() { + init_identity2(); + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start: start2, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start2, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start2[start2.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start2, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} +var startColMsg; +var init_resolve_block_map = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-block-map.js"() { + init_Pair(); + init_YAMLMap(); + init_resolve_props(); + init_util_contains_newline(); + init_util_flow_indent_check(); + init_util_map_includes(); + startColMsg = "All mapping items must start at the same column"; + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start: start2, value: value2 } of bs.items) { + const props = resolveProps(start2, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start2, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} +var init_resolve_block_seq = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-block-seq.js"() { + init_YAMLSeq(); + init_resolve_props(); + init_util_flow_indent_check(); + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end2, offset, reqSpace, onError) { + let comment = ""; + if (end2) { + let hasSpace = false; + let sep = ""; + for (const token of end2) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} +var init_resolve_end = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-end.js"() { + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start: start2, key, sep, value: value2 } = collItem; + const props = resolveProps(start2, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start2) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start2, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end2 = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end2.comment) { + if (coll.comment) + coll.comment += "\n" + end2.comment; + else + coll.comment = end2.comment; + } + coll.range = [fc.offset, cePos, end2.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} +var blockMsg, isBlock; +var init_resolve_flow_collection = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-flow-collection.js"() { + init_identity2(); + init_Pair(); + init_YAMLMap(); + init_YAMLSeq(); + init_resolve_end(); + init_resolve_props(); + init_util_contains_newline(); + init_util_map_includes(); + blockMsg = "Block collections are not allowed within flow collections"; + isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); + } +}); + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} +var init_compose_collection = __esm({ + "node_modules/yaml/browser/dist/compose/compose-collection.js"() { + init_identity2(); + init_Scalar(); + init_YAMLMap(); + init_YAMLSeq(); + init_resolve_block_map(); + init_resolve_block_seq(); + init_resolve_flow_collection(); + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start2 = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start2, start2, start2] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end3 = start2 + header.length; + if (scalar.source) + end3 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start2, end3, end3] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end2 = start2 + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start2, end2, end2] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} +var init_resolve_block_scalar = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-block-scalar.js"() { + init_Scalar(); + } +}); + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end: end2 } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end2, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} +var escapeCodes; +var init_resolve_flow_scalar = __esm({ + "node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js"() { + init_Scalar(); + init_resolve_end(); + escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " + }; + } +}); + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} +var init_compose_scalar = __esm({ + "node_modules/yaml/browser/dist/compose/compose-scalar.js"() { + init_identity2(); + init_Scalar(); + init_resolve_block_scalar(); + init_resolve_flow_scalar(); + } +}); + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} +var init_util_empty_scalar_position = __esm({ + "node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js"() { + } +}); + +// node_modules/yaml/browser/dist/compose/compose-node.js +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end: end2 }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end2; + } + return node; +} +function composeAlias({ options }, { offset, source, end: end2 }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end2, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} +var CN; +var init_compose_node = __esm({ + "node_modules/yaml/browser/dist/compose/compose-node.js"() { + init_Alias(); + init_identity2(); + init_compose_collection(); + init_compose_scalar(); + init_resolve_end(); + init_util_empty_scalar_position(); + CN = { composeNode, composeEmptyNode }; + } +}); + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start: start2, value: value2, end: end2 }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start2, { + indicator: "doc-start", + next: value2 ?? end2?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start2, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end2, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} +var init_compose_doc = __esm({ + "node_modules/yaml/browser/dist/compose/compose-doc.js"() { + init_Document(); + init_compose_node(); + init_resolve_end(); + init_resolve_props(); + } +}); + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer; +var init_composer = __esm({ + "node_modules/yaml/browser/dist/compose/composer.js"() { + init_directives(); + init_Document(); + init_errors3(); + init_identity2(); + init_compose_doc(); + init_resolve_end(); + Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it2 = dc.items[0]; + if (isPair(it2)) + it2 = it2.key; + const cb = it2.commentBefore; + it2.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end2 = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end2.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end2.comment}` : end2.comment; + } + this.doc.range[2] = end2.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } + }; + } +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end2 = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end2)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end: end2 }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end: end2 }; + default: + return { type: "scalar", offset, indent, source, end: end2 }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end2) { + if (end2) + for (const st of end2) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end2 = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end2) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end: end2 }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end2 = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end: end2 }); + } + } +} +var init_cst_scalar = __esm({ + "node_modules/yaml/browser/dist/parse/cst-scalar.js"() { + init_resolve_block_scalar(); + init_resolve_flow_scalar(); + init_errors3(); + init_stringifyString(); + } +}); + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start: start2, key, sep, value: value2 }) { + let res = ""; + for (const st of start2) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} +var stringify2; +var init_cst_stringify = __esm({ + "node_modules/yaml/browser/dist/parse/cst-stringify.js"() { + stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); + } +}); + +// node_modules/yaml/browser/dist/parse/cst-visit.js +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} +var BREAK2, SKIP2, REMOVE2; +var init_cst_visit = __esm({ + "node_modules/yaml/browser/dist/parse/cst-visit.js"() { + BREAK2 = /* @__PURE__ */ Symbol("break visit"); + SKIP2 = /* @__PURE__ */ Symbol("skip children"); + REMOVE2 = /* @__PURE__ */ Symbol("remove item"); + visit2.BREAK = BREAK2; + visit2.SKIP = SKIP2; + visit2.REMOVE = REMOVE2; + visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; + }; + visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); + }; + } +}); + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} +var BOM, DOCUMENT, FLOW_END, SCALAR2, isCollection2, isScalar2; +var init_cst = __esm({ + "node_modules/yaml/browser/dist/parse/cst.js"() { + init_cst_scalar(); + init_cst_stringify(); + init_cst_visit(); + BOM = "\uFEFF"; + DOCUMENT = ""; + FLOW_END = ""; + SCALAR2 = ""; + isCollection2 = (token) => !!token && "items" in token; + isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); + } +}); + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits, tagChars, flowIndicatorChars, invalidAnchorChars, isNotAnchorChar, Lexer; +var init_lexer = __esm({ + "node_modules/yaml/browser/dist/parse/lexer.js"() { + init_cst(); + hexDigits = new Set("0123456789ABCDEFabcdef"); + tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); + flowIndicatorChars = new Set(",[]{}"); + invalidAnchorChars = new Set(" ,[]{}\n\r "); + isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); + Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next2 = this.next ?? "stream"; + while (next2 && (incomplete || this.hasChars(1))) + next2 = yield* this.parseNext(next2); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next2 = this.buffer[indent + offset + 1]; + if (next2 === "\n" || !next2 && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end2 = this.lineEndPos; + if (typeof end2 !== "number" || end2 !== -1 && end2 < this.pos) { + end2 = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end2; + } + if (end2 === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end2 - 1] === "\r") + end2 -= 1; + return this.buffer.substring(this.pos, end2); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next2) { + switch (next2) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next2 = this.charAt(1); + if (this.flowKey || isEmpty(next2) || next2 === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end2 = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end2 !== -1 && this.buffer[end2 + 1] === "'") + end2 = this.buffer.indexOf("'", end2 + 2); + } else { + while (end2 !== -1) { + let n = 0; + while (this.buffer[end2 - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end2 = this.buffer.indexOf('"', end2 + 1); + } + } + const qb = this.buffer.substring(0, end2); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end2 = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end2 === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end2 = this.buffer.length; + } + yield* this.pushToIndex(end2 + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next2 = this.buffer[i2 + 1]; + if (!next2 && !this.atEnd) + return this.setNext("block-scalar"); + if (next2 === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end2 = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next2 = this.buffer[i + 1]; + if (isEmpty(next2) || inFlow && flowIndicatorChars.has(next2)) + break; + end2 = i; + } else if (isEmpty(ch)) { + let next2 = this.buffer[i + 1]; + if (ch === "\r") { + if (next2 === "\n") { + i += 1; + ch = "\n"; + next2 = this.buffer[i + 1]; + } else + end2 = i; + } + if (next2 === "#" || inFlow && flowIndicatorChars.has(next2)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end2 = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end2 + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } + }; + } +}); + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter; +var init_line_counter = __esm({ + "node_modules/yaml/browser/dist/parse/line-counter.js"() { + LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start2 = this.lineStarts[low - 1]; + return { line: low, col: offset - start2 + 1 }; + }; + } + }; + } +}); + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it2 = parent.items[parent.items.length - 1]; + return it2.sep ?? it2.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it2 of fc.items) { + if (it2.sep && !it2.value && !includesToken(it2.start, "explicit-key-ind") && !includesToken(it2.sep, "map-value-ind")) { + if (it2.key) + it2.value = it2.key; + delete it2.key; + if (isFlowToken(it2.value)) { + if (it2.value.end) + arrayPushArray(it2.value.end, it2.sep); + else + it2.value.end = it2.sep; + } else + arrayPushArray(it2.start, it2.sep); + delete it2.sep; + } + } + } +} +var Parser; +var init_parser = __esm({ + "node_modules/yaml/browser/dist/parse/parser.js"() { + init_cst(); + init_lexer(); + Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it2 = top.items[top.items.length - 1]; + if (it2.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it2.sep) { + it2.value = token; + } else { + Object.assign(it2, { key: token, sep: [] }); + this.onKeyLine = !it2.explicitKey; + return; + } + break; + } + case "block-seq": { + const it2 = top.items[top.items.length - 1]; + if (it2.value) + top.items.push({ start: [], value: token }); + else + it2.value = token; + break; + } + case "flow-collection": { + const it2 = top.items[top.items.length - 1]; + if (!it2 || it2.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it2.sep) + it2.value = token; + else + Object.assign(it2, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start2 = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start: start2, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it2 = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it2.value) { + const end2 = "end" in it2.value ? it2.value.end : void 0; + const last = Array.isArray(end2) ? end2[end2.length - 1] : void 0; + if (last?.type === "comment") + end2?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it2.sep) { + it2.sep.push(this.sourceToken); + } else { + it2.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it2.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it2.sep) { + it2.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it2.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end2 = prev?.value?.end; + if (Array.isArray(end2)) { + arrayPushArray(end2, it2.start); + end2.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it2.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it2.sep || it2.explicitKey) && this.type !== "seq-item-ind"; + let start2 = []; + if (atNextItem && it2.sep && !it2.value) { + const nl = []; + for (let i = 0; i < it2.sep.length; ++i) { + const st = it2.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start2 = it2.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it2.value) { + start2.push(this.sourceToken); + map3.items.push({ start: start2 }); + this.onKeyLine = true; + } else if (it2.sep) { + it2.sep.push(this.sourceToken); + } else { + it2.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it2.sep && !it2.explicitKey) { + it2.start.push(this.sourceToken); + it2.explicitKey = true; + } else if (atNextItem || it2.value) { + start2.push(this.sourceToken); + map3.items.push({ start: start2, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it2.explicitKey) { + if (!it2.sep) { + if (includesToken(it2.start, "newline")) { + Object.assign(it2, { key: null, sep: [this.sourceToken] }); + } else { + const start3 = getFirstKeyStartProps(it2.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start3, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it2.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it2.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it2.key) && !includesToken(it2.sep, "newline")) { + const start3 = getFirstKeyStartProps(it2.start); + const key = it2.key; + const sep = it2.sep; + sep.push(this.sourceToken); + delete it2.key; + delete it2.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start3, key, sep }] + }); + } else if (start2.length > 0) { + it2.sep = it2.sep.concat(start2, this.sourceToken); + } else { + it2.sep.push(this.sourceToken); + } + } else { + if (!it2.sep) { + Object.assign(it2, { key: null, sep: [this.sourceToken] }); + } else if (it2.value || atNextItem) { + map3.items.push({ start: start2, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it2.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it2.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it2.value) { + map3.items.push({ start: start2, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it2.sep) { + this.stack.push(fs2); + } else { + Object.assign(it2, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it2.explicitKey && it2.sep && !includesToken(it2.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start: start2 }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it2 = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it2.value) { + const end2 = "end" in it2.value ? it2.value.end : void 0; + const last = Array.isArray(end2) ? end2[end2.length - 1] : void 0; + if (last?.type === "comment") + end2?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it2.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it2.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it2.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end2 = prev?.value?.end; + if (Array.isArray(end2)) { + arrayPushArray(end2, it2.start); + end2.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it2.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it2.value || this.indent <= seq2.indent) + break; + it2.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it2.value || includesToken(it2.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it2.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it2 = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it2 || it2.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it2.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it2 || it2.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it2.sep) + it2.sep.push(this.sourceToken); + else + Object.assign(it2, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it2 || it2.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it2.sep) + it2.sep.push(this.sourceToken); + else + it2.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it2 || it2.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it2.sep) + this.stack.push(fs2); + else + Object.assign(it2, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start2 = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start: start2, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start2 = getFirstKeyStartProps(prev); + start2.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start2 = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start2, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start2.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + }; + } +}); + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} +var init_public_api = __esm({ + "node_modules/yaml/browser/dist/public-api.js"() { + init_composer(); + init_Document(); + init_errors3(); + init_log(); + init_identity2(); + init_line_counter(); + init_parser(); + } +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); +var init_dist5 = __esm({ + "node_modules/yaml/browser/dist/index.js"() { + init_composer(); + init_Document(); + init_Schema(); + init_errors3(); + init_Alias(); + init_identity2(); + init_Pair(); + init_Scalar(); + init_YAMLMap(); + init_YAMLSeq(); + init_cst(); + init_lexer(); + init_line_counter(); + init_parser(); + init_public_api(); + init_visit(); + } +}); + +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); +var browser_default; +var init_browser = __esm({ + "node_modules/yaml/browser/index.js"() { + init_dist5(); + init_dist5(); + browser_default = dist_exports4; + } +}); + // node_modules/@earendil-works/pi-durable/dist/tools/env.js function requireEnv(api) { if (api.env === void 0) @@ -31061,7 +38267,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -31186,7 +38392,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -32317,8 +39523,8 @@ var init_string_enum = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -32398,7 +39604,7 @@ __export(dist_exports4, { withClientIdentity: () => withClientIdentity, withoutInitialSystemMessage: () => withoutInitialSystemMessage }); -var init_dist5 = __esm({ +var init_dist6 = __esm({ "node_modules/@earendil-works/pi-ai/dist/index.js"() { init_lazy(); init_context2(); @@ -32452,11 +39658,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -32693,7 +39899,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -32922,7 +40128,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -32940,8 +40151,9 @@ var ops2, encoder4, decoder4, ExtensionState, Metadata, fs; var init_extensions = __esm({ "extensions.ts"() { init_dist4(); + init_browser(); init_tools(); - init_dist5(); + init_dist6(); init_models(); init_dist3(); init_context(); @@ -33073,11 +40285,11 @@ async function fixture(clock = {}) { const c = await harness.conversation(id, BACKGROUND_CONTEXT); await (await c.submit({ type: "input", content }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); }; - const ultimate = async () => { + const standing = async () => { const c = await harness.createConversation({ ownership: { kind: "ownerless" } }, BACKGROUND_CONTEXT); await c.configure({ model: { provider: "faux", modelId: "faux-1" } }, BACKGROUND_CONTEXT); await harness.commit(async (tx) => { - (await tx.doc(Standing, root.id)).ultimate = c.id; + (await tx.doc(Standing, root.id))["$standing"] = c.id; }, BACKGROUND_CONTEXT); return c.id; }; @@ -33092,7 +40304,7 @@ async function fixture(clock = {}) { await loader.close(); await harness.close(BACKGROUND_CONTEXT); await storage.close(); - } }, ultimate, type, ask, answer: (args) => question.actions.answer(args, action()), dismiss: (messageId) => question.actions.dismiss({ messageId }, action()), log, entries: entries2, observed, settled, hear: (fn) => heard = fn }; + } }, standing, type, ask, answer: (args) => question.actions.answer(args, action()), dismiss: (messageId) => question.actions.dismiss({ messageId }, action()), log, entries: entries2, observed, settled, hear: (fn) => heard = fn }; } var next; var init_goal_questions_fixture = __esm({ @@ -33114,10 +40326,10 @@ function fakeTx(newer = []) { const docs = /* @__PURE__ */ new Map(); const entries2 = [ ...newer, - { id: 30, conversationId: ULTIMATE, model: [{ role: "user", content: "no images" }] }, + { id: 30, conversationId: STANDING, model: [{ role: "user", content: "no images" }] }, { id: 20, - conversationId: ULTIMATE, + conversationId: STANDING, model: [{ role: "toolResult", content: [{ type: "text", text: "shot" }, screenshot] }] }, { id: 10, conversationId: 9, model: [{ role: "user", content: [screenshot] }] } @@ -33133,7 +40345,7 @@ function fakeTx(newer = []) { if (!docs.has(key)) docs.set( key, - def.kind === "ultimate.standing-agents" ? { ultimate: ULTIMATE } : def.initial() + def.kind === "standing.standing-agents" ? { "$standing": STANDING } : def.initial() ); return overlay(docs.get(key)); }, @@ -33178,14 +40390,14 @@ function fakeHost(tx) { }; return { host, ledger, service, sync }; } -var reminderTask, goalExtension, act, actions, end, Goals, openGoal, start, TRIES, ULTIMATE, screenshot, overlay; +var reminderTask, goalExtension, act, actions, end, Goals, openGoal, start, TRIES, STANDING, screenshot, overlay; var init_goal_cases = __esm({ async "goal-cases.ts"() { init_context(); init_goal_questions_test_support(); ({ reminderTask } = await import(`${globalThis.goalBase}/goal/reminder.ts`)); ({ default: goalExtension, act, actions, end, Goals, openGoal, start, TRIES } = await import(`${globalThis.goalBase}/goal/server.ts`)); - ULTIMATE = 5; + STANDING = 5; screenshot = { type: "image", data: "aGk=", mimeType: "image/png" }; overlay = (value2) => new Proxy(value2, { get: (target, key) => { @@ -33209,26 +40421,26 @@ var init_goal_cases = __esm({ }); it("blocks a criterion after repeated failed tries and finishes with the outcome", async () => { const tx = fakeTx(); - await expect(act(tx, ULTIMATE, { action: "met", n: 1 }, 0)).rejects.toThrow("No hands-off goal"); + await expect(act(tx, STANDING, { action: "met", n: 1 }, 0)).rejects.toThrow("No hands-off goal"); await start(tx, "Goal", 0); - await act(tx, ULTIMATE, { action: "criteria", criteria: ["Loads in 1s", "Tests pass"] }, 0); - await expect(act(tx, ULTIMATE, { action: "met", n: 3 }, 0)).rejects.toThrow("No criterion 3"); - for (let i = 1; i < TRIES; i++) await act(tx, ULTIMATE, { action: "failed", n: 1 }, 0); + await act(tx, STANDING, { action: "criteria", criteria: ["Loads in 1s", "Tests pass"] }, 0); + await expect(act(tx, STANDING, { action: "met", n: 3 }, 0)).rejects.toThrow("No criterion 3"); + for (let i = 1; i < TRIES; i++) await act(tx, STANDING, { action: "failed", n: 1 }, 0); expect((await openGoal(tx)).criteria[0]).toMatchObject({ status: "open", tries: TRIES - 1 }); - const last = await act(tx, ULTIMATE, { action: "failed", n: 1 }, 0); + const last = await act(tx, STANDING, { action: "failed", n: 1 }, 0); expect(last.answer).toContain("blocked"); expect((await openGoal(tx)).criteria[0].status).toBe("blocked"); - await act(tx, ULTIMATE, { action: "criteria", criteria: ["Loads in 1s", "Lint passes"] }, 0); + await act(tx, STANDING, { action: "criteria", criteria: ["Loads in 1s", "Lint passes"] }, 0); expect((await openGoal(tx)).criteria.map((item) => item.status)).toEqual(["blocked", "open"]); - await expect(act(tx, ULTIMATE, { action: "finish", summary: "x" }, 0)).rejects.toThrow("outcome"); + await expect(act(tx, STANDING, { action: "finish", summary: "x" }, 0)).rejects.toThrow("outcome"); const done = await act( tx, - ULTIMATE, + STANDING, { action: "finish", outcome: "blocked", summary: "Stuck" }, 4 ); expect(done.ended).toMatchObject({ - ended: { by: "ultimate", outcome: "blocked", summary: "Stuck" } + ended: { by: "standing", outcome: "blocked", summary: "Stuck" } }); expect(await openGoal(tx)).toBeUndefined(); }); @@ -33236,11 +40448,11 @@ var init_goal_cases = __esm({ const tx = fakeTx(); await start(tx, "Goal", 0); await expect( - act(tx, ULTIMATE, { action: "decide", question: "Go?", picked: "Yes" }, 0) + act(tx, STANDING, { action: "decide", question: "Go?", picked: "Yes" }, 0) ).rejects.toThrow("reason"); await act( tx, - ULTIMATE, + STANDING, { action: "decide", question: "Approve?", @@ -33252,23 +40464,23 @@ var init_goal_cases = __esm({ 1 ); await expect( - act(tx, ULTIMATE, { action: "decide", question: "q", picked: "p", reason: "r", images: 10 }, 2) + act(tx, STANDING, { action: "decide", question: "q", picked: "p", reason: "r", images: 10 }, 2) ).rejects.toThrow("has no images"); expect((await openGoal(tx)).decisions).toEqual([ { at: 1, question: "Approve?", picked: "Yes", reason: "Meets 1", conversation: 7, images: 20 } ]); }); it(`never takes an earlier turn's screenshot for images: "latest"`, async () => { - const tx = fakeTx([{ id: 40, kind: "pi.user", conversationId: ULTIMATE, model: [] }]); + const tx = fakeTx([{ id: 40, kind: "pi.user", conversationId: STANDING, model: [] }]); await start(tx, "Goal", 0); const decide = { action: "decide", question: "q", picked: "p", reason: "r" }; - await expect(act(tx, ULTIMATE, { ...decide, images: "latest" }, 1)).rejects.toThrow( + await expect(act(tx, STANDING, { ...decide, images: "latest" }, 1)).rejects.toThrow( "no images in this turn" ); - await act(tx, ULTIMATE, { ...decide, images: 20 }, 2); + await act(tx, STANDING, { ...decide, images: 20 }, 2); expect((await openGoal(tx)).decisions).toMatchObject([{ images: 20 }]); }); - it("notes the open goal on @ultimate's runs only, and lets only @ultimate keep it", async () => { + it("notes the open goal on @standing's runs only, and lets only @standing keep it", async () => { const tx = fakeTx(); const extension = goalExtension({ doc: () => void 0, @@ -33277,10 +40489,10 @@ var init_goal_cases = __esm({ }); const hooks = extension.hooks[0].handlers; const before = (conversationId, kind = "pi.user") => hooks.beforeInput({ kind }, { tx, conversationId }, BACKGROUND_CONTEXT); - expect(await before(ULTIMATE)).toBeUndefined(); + expect(await before(STANDING)).toBeUndefined(); await start(tx, "Make it fast", 0); expect(await before(9)).toBeUndefined(); - const note = (await before(ULTIMATE)).entries[0]; + const note = (await before(STANDING)).entries[0]; expect(note.kind).toBe("goal.note"); expect(note.model[0].content).toContain( "Hands-off goal 1, granted by the user, who is away: Make it fast" @@ -33291,17 +40503,17 @@ var init_goal_cases = __esm({ { conversationId, commit: (fn) => fn(tx) }, void 0 ); - await expect(run2(9, { action: "met", n: 1 })).rejects.toThrow("Only @ultimate"); - expect(await run2(ULTIMATE, { action: "criteria", criteria: ["Fast"] })).toEqual({ + await expect(run2(9, { action: "met", n: 1 })).rejects.toThrow("Only the standing agent"); + expect(await run2(STANDING, { action: "criteria", criteria: ["Fast"] })).toEqual({ content: [{ type: "text", text: "Goal 1 has 1 criteria." }] }); expect((await tx.doc(Goals, 1)).goals[0].criteria).toHaveLength(1); - await run2(ULTIMATE, { action: "finish", outcome: "met", summary: "Done" }); + await run2(STANDING, { action: "finish", outcome: "met", summary: "Done" }); expect(tx.tasks).toEqual([ - { name: "goal.deliver", input: expect.objectContaining({ to: ULTIMATE, kind: "goal.report" }) }, + { name: "goal.deliver", input: expect.objectContaining({ to: STANDING, kind: "goal.report" }) }, { name: "goal.reminder", input: { goal: 1 } } ]); - expect(await before(ULTIMATE)).toBeUndefined(); + expect(await before(STANDING)).toBeUndefined(); }); it("keeps a reminder while the goal is open: paused while waiting on the user, gone once ended", async () => { const tx = fakeTx(); @@ -33310,13 +40522,13 @@ var init_goal_cases = __esm({ const tool = extension.tools.find((candidate) => candidate.name === "goal"); const run2 = (args) => tool.execute( args, - { conversationId: ULTIMATE, commit: (fn) => fn(tx) }, + { conversationId: STANDING, commit: (fn) => fn(tx) }, void 0 ); await actions.start({ text: "Make it fast" }, { host }); await service.create({ name: "Goal reminder \xB7 goal 1", - subscribers: ["@ultimate"], + subscribers: ["@standing"], key: "goal.reminder:1" }); (await openGoal(tx)).waiting = { reason: "Which account?", at: 0 }; @@ -33325,7 +40537,7 @@ var init_goal_cases = __esm({ { id: "A1", name: "Goal reminder \xB7 goal 1", - subscribers: ["@ultimate"], + subscribers: ["@standing"], key: "goal.reminder:1", enabled: false } @@ -33336,7 +40548,7 @@ var init_goal_cases = __esm({ expect(ledger.get("A1").enabled).toBe(true); ledger.get("A1").name = "Night check"; const hooks = extension.hooks[0].handlers; - const note = async (input) => (await hooks.beforeInput(input, { tx, conversationId: ULTIMATE }, BACKGROUND_CONTEXT)).entries[0].model[0].content; + const note = async (input) => (await hooks.beforeInput(input, { tx, conversationId: STANDING }, BACKGROUND_CONTEXT)).entries[0].model[0].content; expect(await note({ kind: "automations.fired", data: { id: "A1" } })).toContain( "This is the goal reminder" ); @@ -33379,7 +40591,7 @@ var init_goal_cases = __esm({ expect( await hooks.beforeInput( { kind: "goal.started" }, - { tx, conversationId: ULTIMATE }, + { tx, conversationId: STANDING }, BACKGROUND_CONTEXT ) ).toBeUndefined(); @@ -33433,7 +40645,7 @@ var init_questions_cases = __esm({ describe2("questions on a message", () => { it("are stored as the tool validated them, only on reply-expected messages to the user", async () => { const f = await fixture2(); - const id = await f.ultimate(); + const id = await f.standing(); const sent = await f.ask(id, { text: "Decide these.", questions: decisions }); expect(sent.error).toBeUndefined(); expect(sent.message).toMatchObject({ state: "delivered", questions: decisions }); @@ -33450,7 +40662,7 @@ var init_questions_cases = __esm({ }); it("refuses questions the card could not answer, naming the question", async () => { const f = await fixture2(); - const id = await f.ultimate(); + const id = await f.standing(); const refused = async (questions, reason) => { const { error } = await f.ask(id, { text: "Decide.", questions }); expect(error).toContain(reason); @@ -33511,7 +40723,7 @@ var init_questions_cases = __esm({ }); it("answers in the message numbering for every kind, with a note after the answers", async () => { const f = await fixture2(); - const id = await f.ultimate(); + const id = await f.standing(); const { message } = await f.ask(id, { text: "Decide these.", questions: decisions }); expect(userActions).toEqual(["answer", "dismiss"]); await expect( @@ -33558,7 +40770,7 @@ var init_questions_cases = __esm({ }); it("sends a note on its own, and free text for a message without questions", async () => { const f = await fixture2(); - const id = await f.ultimate(); + const id = await f.standing(); const { message } = await f.ask(id, { text: "Decide these.", questions: decisions }); await expect(f.answer({ messageId: message.id, answers: [], note: " " })).rejects.toThrow( "Invalid answers" @@ -33584,9 +40796,9 @@ var init_questions_cases = __esm({ "These questions are no longer open" ); }); - it("keeps @ultimate's open message open until its card answers it, naming it by its questions", async () => { + it("keeps @standing's open message open until its card answers it, naming it by its questions", async () => { const f = await fixture2(); - const id = await f.ultimate(); + const id = await f.standing(); const { message } = await f.ask(id, { text: "Decide these.", questions: decisions }); await f.type( f.opened.root.id, @@ -33614,7 +40826,7 @@ var init_questions_cases = __esm({ }); it("dismisses one open question with a one-way note that starts no run, leaving the others open", async () => { const f = await fixture2(); - const id = await f.ultimate(); + const id = await f.standing(); const first = (await f.ask(id, { text: "Keep it running?", questions: [decisions[2]] })).message; const second = (await f.ask(id, { text: "Which layout?" })).message; const before = (await f.entries(id)).filter((entry2) => entry2.kind === "pi.assistant").length; @@ -33742,7 +40954,7 @@ var init_goal_reminder_cases = __esm({ return () => timers.delete(timer); } }); try { - const id = await f.ultimate(); + const id = await f.standing(); const { harness } = f.opened; const goal = await import( /* @vite-ignore */ diff --git a/host/js/goal-questions-test-support.ts b/host/js/goal-questions-test-support.ts index 9818efe..fe26abb 100644 --- a/host/js/goal-questions-test-support.ts +++ b/host/js/goal-questions-test-support.ts @@ -1,4 +1,4 @@ -/** Minimal assertions for the imported Ultimate cases, without Node or Vitest. */ +/** Minimal assertions for the imported Standing agent cases, without Node or Vitest. */ export const cases: {name:string;run:()=>any}[]=[] export const it=(name:string,run:()=>any)=>cases.push({name,run}) export const describe=(_name:string,run:()=>any)=>run() diff --git a/host/js/goal-questions-test.ts b/host/js/goal-questions-test.ts index ea03ef5..b4dab34 100644 --- a/host/js/goal-questions-test.ts +++ b/host/js/goal-questions-test.ts @@ -1,4 +1,4 @@ -/** Ultimate goal and question-card cases execute in the world loader. */ +/** Standing agent goal and question-card cases execute in the world loader. */ import {fixture} from './goal-questions-fixture' import {cases,cleanups} from './goal-questions-test-support' const initial=await fixture() diff --git a/host/js/goal-reminder-cases.ts b/host/js/goal-reminder-cases.ts index fbafcd3..9f1804c 100644 --- a/host/js/goal-reminder-cases.ts +++ b/host/js/goal-reminder-cases.ts @@ -9,7 +9,7 @@ it('fires one goal reminder through automations',async()=>{ const timer={at:now+delay,callback};timers.add(timer);return()=>timers.delete(timer) }}) try { - const id=await f.ultimate();const {harness}=f.opened + const id=await f.standing();const {harness}=f.opened const goal=await import(/* @vite-ignore */ `${f.base}/goal/server.ts`) const {Automations}=await import(/* @vite-ignore */ `${f.base}/automations/server.ts`) await goal.actions.start({text:'Ship the goal'},{host:f.host}) diff --git a/host/js/harness-api-test-bundle.js b/host/js/harness-api-test-bundle.js index cbd9409..7c5665c 100644 --- a/host/js/harness-api-test-bundle.js +++ b/host/js/harness-api-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root, base, fragment) { let node = root; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next2) => { + const set2 = (key, next2) => { if (next2 === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next2 = this.convert(properties[key], base, next2); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next2 = this.convert(schema, base, next2); + next2 = this.convert(schema4, base, next2); } if (!matched && additional !== void 0) next2 = this.convert(additional, base, next2); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next2 = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next2 = this.coerceTypes(next2, member, b); - if (Array.isArray(schema.anyOf)) - next2 = this.coerceUnion(next2, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next2 = this.coerceUnion(next2, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next2 = this.coerceUnion(next2, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next2 = this.coerceUnion(next2, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next2, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next2)) - next2 = this.coerceProperties(next2, schema, b); + next2 = this.coerceProperties(next2, schema4, b); if (types.includes("array") && Array.isArray(next2)) - next2 = this.coerceItems(next2, schema, b); + next2 = this.coerceItems(next2, schema4, b); return next2; } coerceUnion(value2, branches, base) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next2) => { + const set2 = (key, next2) => { if (next2 === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next2 = map2(items[i], i); + const next2 = map3(items[i], i); if (next2 === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial2, guard, options) { + constructor(key, schema4, initial2, guard, options) { super(key, options); if (initial2 !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial2.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial2.value); + this.schema = schema4; this.#tracker = track({ v: initial2?.value ?? null }); this.#guard = guard; this.#initialized = initial2 !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial2, options = {}) { + state(name, schema4, initial2, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial2) ? initial2.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial2 } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial2 } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry.name, set); + let set2 = this.#subscribers.get(registry.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id2 of tx.createdTaskIds()) this.#taskDocuments.set(id2, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -20108,7 +20108,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id2, action] of actions) { let stored = this.state.documents.get(id2); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id2, "document"); this.state.documents.set(id2, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id2); this.nextId = Math.max(this.nextId, id2 + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28718,8 +28718,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -28825,8 +28825,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -28917,20 +28917,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -28966,9 +28966,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next2++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next2++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -28976,8 +28976,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -28995,10 +28995,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -29434,7 +29434,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id2 === void 0 ? void 0 : idFromNumber(id2); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -29442,7 +29442,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -29487,21 +29487,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id2, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id2, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id2, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id2, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id2); record2 = parseJson(row.record); @@ -29511,12 +29511,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id2); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id2, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id2, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id2); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id2); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id2); @@ -29571,6 +29571,6646 @@ async function openStorage(path) { return SqliteStorage.open(database); } +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next2 = text[i + 1]; + if (next2 && next2 !== " " && next2 !== "\n" && next2 !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f2 = str2.substring(dot + 1).replace(/_/g, ""); + if (f2[f2.length - 1] === "0") + node.minFractionDigits = f2.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next: next2, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next2?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next2 && next2.type !== "space" && next2.type !== "newline" && next2.type !== "comma" && (next2.type !== "scalar" || next2.source !== "")) { + onError(next2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next2?.type === "block-map" || next2?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next2 = this.next ?? "stream"; + while (next2 && (incomplete || this.hasChars(1))) + next2 = yield* this.parseNext(next2); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next2 = this.buffer[indent + offset + 1]; + if (next2 === "\n" || !next2 && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next2) { + switch (next2) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next2 = this.charAt(1); + if (this.flowKey || isEmpty(next2) || next2 === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next2 = this.buffer[i2 + 1]; + if (!next2 && !this.atEnd) + return this.setNext("block-scalar"); + if (next2 === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next2 = this.buffer[i + 1]; + if (isEmpty(next2) || inFlow && flowIndicatorChars.has(next2)) + break; + end = i; + } else if (isEmpty(ch)) { + let next2 = this.buffer[i + 1]; + if (ch === "\r") { + if (next2 === "\n") { + i += 1; + ch = "\n"; + next2 = this.buffer[i + 1]; + } else + end = i; + } + if (next2 === "#" || inFlow && flowIndicatorChars.has(next2)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -30007,7 +36647,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -30132,7 +36772,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -31043,8 +37683,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -31246,11 +37886,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after2, visit) { +async function scan(tx, log, after2, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after2 + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -31467,7 +38107,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -31696,7 +38336,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f2) => f2.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -31808,11 +38453,11 @@ async function fixture(clock = {}) { const c = await harness2.conversation(id2, BACKGROUND_CONTEXT); await (await c.submit({ type: "input", content }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); }; - const ultimate = async () => { + const standing = async () => { const c = await harness2.createConversation({ ownership: { kind: "ownerless" } }, BACKGROUND_CONTEXT); await c.configure({ model: { provider: "faux", modelId: "faux-1" } }, BACKGROUND_CONTEXT); await harness2.commit(async (tx) => { - (await tx.doc(Standing, root.id)).ultimate = c.id; + (await tx.doc(Standing, root.id))["$standing"] = c.id; }, BACKGROUND_CONTEXT); return c.id; }; @@ -31827,7 +38472,7 @@ async function fixture(clock = {}) { await loader.close(); await harness2.close(BACKGROUND_CONTEXT); await storage.close(); - } }, ultimate, type, ask, answer: (args) => question2.actions.answer(args, action()), dismiss: (messageId) => question2.actions.dismiss({ messageId }, action()), log, entries: entries2, observed, settled, hear: (fn) => heard = fn }; + } }, standing, type, ask, answer: (args) => question2.actions.answer(args, action()), dismiss: (messageId) => question2.actions.dismiss({ messageId }, action()), log, entries: entries2, observed, settled, hear: (fn) => heard = fn }; } // harness-api.ts @@ -31897,6 +38542,7 @@ function harnessApi(harness2, models, extensions, context) { }; try { if (input.method === "GET" && path === "/conversations") { + const standing = await extensions.standing?.() ?? null; const records = await harness2.commit(async (tx) => { const all = []; let cursor; @@ -31915,7 +38561,7 @@ function harnessApi(harness2, models, extensions, context) { const started = await harness2.snapshot(Started2, record2.id, context); return { ...record2, title: metadata?.title ?? "", agent, starter: started?.by ?? null, concluded: concluded.has(record2.id), running: !!live?.run }; })); - reply(200, { conversations }); + reply(200, { conversations, standing }); return; } if (input.method === "GET" && path === "/events") { @@ -31927,16 +38573,6 @@ function harnessApi(harness2, models, extensions, context) { reply(200, extensions.state()); return; } - if (input.method === "GET" && path === "/families") { - let families = {}; - try { - families = JSON.parse(await fs.read("/src/sausage/agents/models.json")); - } catch (error) { - if (error.code !== "not_found") throw error; - } - reply(200, { families }); - return; - } if (input.method === "GET" && path === "/models") { reply(200, { models: models.getAllModels().map(({ id: id2, name, provider: provider2, contextWindow, maxTokens, reasoning, cost }) => ({ id: id2, name, provider: provider2, contextWindow, maxTokens, reasoning, cost })) }); return; @@ -31991,7 +38627,7 @@ function harnessApi(harness2, models, extensions, context) { } // input.ts -async function serve(harness2, context, afterSubmit, api2) { +async function serve(harness2, context, afterSubmit, api2, defaultConversation) { const pending = /* @__PURE__ */ new Set(); const track2 = (work) => { const task = work.catch((error) => Deno.core.ops.op_output(`${String(error)} @@ -32014,8 +38650,9 @@ async function serve(harness2, context, afterSubmit, api2) { track2(api2.handle(input)); continue; } - const conversation = await harness2.conversation(input.conversation, context); - if (!conversation) throw new Error(`Unknown conversation: ${input.conversation}`); + const id2 = defaultConversation ? await defaultConversation() : input.conversation; + const conversation = await harness2.conversation(id2, context); + if (!conversation) throw new Error(`Unknown conversation: ${id2}`); const submission2 = await conversation.submit({ type: "input", content: input.content, @@ -32040,11 +38677,12 @@ var curl = async (path, body) => { assert(result.code === 0, `curl failed: ${result.stderr}`); return JSON.parse(result.stdout); }; -var id = await f.ultimate(); +var id = await f.standing(); var question = await f.ask(id, { text: "Choose.", questions: [{ text: "Name", kind: "text", ref: "1" }] }); assert(question.message, "Question fixture"); var listed = await curl("/conversations"); assert(listed.conversations.some((c) => c.id === id && c.agent && !c.running), "Conversation list"); +assert(listed.standing.name === "standing" && listed.standing.conversationId === id, "Conversation list identifies the configured standing conversation"); var initial = await curl(`/conversations/${id}/entries`); var after = initial.entries.at(-1).id; var answer2 = await curl("/extensions/questions/actions/answer", { args: { messageId: question.message.id, answers: [{ question: "Name", answer: "API choice" }] } }); @@ -32052,7 +38690,7 @@ assert(!answer2.error, JSON.stringify(answer2)); await f.settled(); assert(JSON.stringify(await f.entries(id)).includes("API choice"), "Question answer reaches asker"); assert((await curl("/models")).models.length > 0, "Models"); -assert((await curl("/families")).families.default, "Families"); +assert((await curl("/families")).error, "The obsolete families route is absent"); assert((await curl("/extensions")).good, "Extension status"); assert(Array.isArray((await curl("/credential-requests")).requests), "Credential requests"); assert((await curl("/unknown")).error, "Unknown route"); diff --git a/host/js/harness-api-test.ts b/host/js/harness-api-test.ts index e1f3e17..dc88a1a 100644 --- a/host/js/harness-api-test.ts +++ b/host/js/harness-api-test.ts @@ -14,11 +14,12 @@ const curl=async(path:string,body?:any)=>{ assert(result.code===0,`curl failed: ${result.stderr}`); return JSON.parse(result.stdout); }; -const id=await f.ultimate(); +const id=await f.standing(); const question=await f.ask(id,{text:'Choose.',questions:[{text:'Name',kind:'text',ref:'1'}]}); assert(question.message,'Question fixture'); const listed=await curl('/conversations'); assert(listed.conversations.some((c:any)=>c.id===id && c.agent && !c.running),'Conversation list'); +assert(listed.standing.name==='standing'&&listed.standing.conversationId===id,'Conversation list identifies the configured standing conversation'); const initial=await curl(`/conversations/${id}/entries`); const after=initial.entries.at(-1).id; const answer=await curl('/extensions/questions/actions/answer',{args:{messageId:question.message.id,answers:[{question:'Name',answer:'API choice'}]}}); @@ -26,7 +27,7 @@ assert(!answer.error,JSON.stringify(answer)); await f.settled(); assert(JSON.stringify(await f.entries(id)).includes('API choice'),'Question answer reaches asker'); assert((await curl('/models')).models.length>0,'Models'); -assert((await curl('/families')).families.default,'Families'); +assert((await curl('/families')).error,'The obsolete families route is absent'); assert((await curl('/extensions')).good,'Extension status'); assert(Array.isArray((await curl('/credential-requests')).requests),'Credential requests'); assert((await curl('/unknown')).error,'Unknown route'); diff --git a/host/js/harness-api.ts b/host/js/harness-api.ts index 9707cd0..f7ffe2b 100644 --- a/host/js/harness-api.ts +++ b/host/js/harness-api.ts @@ -1,6 +1,6 @@ // The world chat API runs in the same harness as turns and extension actions. import { AgentDoc, LiveDoc, defineDoc } from '@earendil-works/pi-durable'; -import { Metadata, fs } from './extensions'; +import { Metadata } from './extensions'; import { eventLog } from './events'; const Concluded = defineDoc({kind:'conversations.concluded',version:1,scope:'session',checkpointWhen:()=>false,initial:()=>({ids:[]})}); const Started = defineDoc({kind:'board.started',version:1,scope:'conversation',history:'latest',fork:'initial',checkpointWhen:()=>false,initial:()=>({})}); @@ -51,6 +51,7 @@ export function harnessApi(harness:any, models:any, extensions:any, context:any) const reply=(status:number,body:any)=>{send(input.id,{status,body});send(input.id,null);}; try { if(input.method==='GET' && path==='/conversations') { + const standing=await extensions.standing?.() ?? null; const records=await harness.commit(async(tx:any)=>{ const all:any[]=[];let cursor:any; do {const page=await tx.scanConversations({},256,cursor);all.push(...page.items);cursor=page.next;}while(cursor); @@ -64,17 +65,13 @@ export function harnessApi(harness:any, models:any, extensions:any, context:any) const started:any=await harness.snapshot(Started,record.id,context); return {...record,title:metadata?.title??'',agent,starter:started?.by??null,concluded:concluded.has(record.id),running:!!live?.run}; })); - reply(200,{conversations});return; + reply(200,{conversations,standing});return; } if(input.method==='GET' && path==='/events') { const cursor=integer(url.searchParams.get('after'),0); await follow(input,async(after)=>log.recent({since:after,order:'ascending',limit:256}),cursor);return; } if(input.method==='GET' && path==='/extensions') {reply(200,extensions.state());return;} - if(input.method==='GET' && path==='/families') { - let families={};try{families=JSON.parse(await fs.read('/src/sausage/agents/models.json'));}catch(error){if((error as any).code!=='not_found')throw error;} - reply(200,{families});return; - } if(input.method==='GET' && path==='/models') {reply(200,{models:models.getAllModels().map(({id,name,provider,contextWindow,maxTokens,reasoning,cost}:any)=>({id,name,provider,contextWindow,maxTokens,reasoning,cost}))});return;} const action=/^\/extensions\/([^/]+)\/actions\/([^/]+)$/.exec(path); if(input.method==='POST' && action) { diff --git a/host/js/input.ts b/host/js/input.ts index 82c09c7..fbbbc85 100644 --- a/host/js/input.ts +++ b/host/js/input.ts @@ -1,5 +1,5 @@ // EOF and Stop drain submissions. Shutdown cancels invocations and preserves durable tasks for restart. -export async function serve(harness: any, context: any, afterSubmit?: () => Promise, api?: any) { +export async function serve(harness: any, context: any, afterSubmit?: () => Promise, api?: any, defaultConversation?: () => Promise) { const pending = new Set>(); const track = (work: Promise) => { const task = work.catch(error => Deno.core.ops.op_output(`${String(error)}\n`)).finally(() => pending.delete(task)); @@ -22,8 +22,9 @@ export async function serve(harness: any, context: any, afterSubmit?: () => Prom track(api.handle(input)); continue; } - const conversation = await harness.conversation(input.conversation, context); - if (!conversation) throw new Error(`Unknown conversation: ${input.conversation}`); + const id = defaultConversation ? await defaultConversation() : input.conversation; + const conversation = await harness.conversation(id, context); + if (!conversation) throw new Error(`Unknown conversation: ${id}`); const submission = await conversation.submit({ type: 'input', content: input.content, requestId: input.requestId, }, context); diff --git a/host/js/main.ts b/host/js/main.ts index bbb85a2..6206639 100644 --- a/host/js/main.ts +++ b/host/js/main.ts @@ -1,7 +1,7 @@ -// Durable root conversation and console. SQLite stays outside the world. +// The standing conversation serves the console and chat. SQLite stays outside the world. import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context'; import { proxyModels } from './proxy-models'; -import { Harness, AgentDoc, createRegistry } from '@earendil-works/pi-durable'; +import { Harness, createRegistry } from '@earendil-works/pi-durable'; import { CodingTools } from './environment'; import { openStorage } from './sqlite'; import { environment, conversationChains } from './environment'; @@ -9,10 +9,8 @@ import { CredentialRequests, startRequests } from './credentials'; import { serve } from './input'; import { harnessApi } from './harness-api'; import { loadExtensions } from './extensions'; -const proxy = Deno.core.ops.op_model_proxy(); -if (!proxy?.base_url || !proxy?.api_key) throw new Error('The llm-proxy credential is required'); -const models = await proxyModels(proxy); -const model = models.getModel('openai', 'gpt-6.1-sol'); +const proxy = await Deno.core.ops.op_model_proxy(); +const models = await proxyModels(proxy, () => Deno.core.ops.op_model_proxy()); const registry = createRegistry(); registry.install(CodingTools); registry.install(CredentialRequests); @@ -22,14 +20,13 @@ const harness = await Harness.open(storage, { env: async (target: any) => environment(target.cwd ?? '/', await chain(target.conversationId)), }, context); const chain = conversationChains(harness, context); -const root = await harness.root(context, { agent: { model: { provider: 'openai', modelId: model.id }, thinkingLevel: 'low', cwd: '/' } }); -// T32 stored this exact built-in list in the console root. Use registry defaults now. -const storedAgent = await harness.snapshot(AgentDoc, root.id, context); -if (Array.isArray(storedAgent?.extensions) && storedAgent.extensions.length === 2 && - [CodingTools, CredentialRequests].every(extension => storedAgent.extensions.includes(extension.name))) { - await root.configure({ extensions: null }, context); -} -const watch = await root.watch(context); +await harness.root(context, {agent:{cwd:'/src/sausage'}}); +const stopRequests = await startRequests(harness, context); +const extensions = await loadExtensions(harness, registry, storage, models, context, [CodingTools, CredentialRequests]); +const standing = await extensions.standing(); +if (!standing) throw new Error('The world needs the models and subagents extensions for its standing agent'); +const conversation = (await harness.conversation(standing.conversationId, context))!; +const watch = await conversation.watch(context); const emitted = new Map(); let partial = ''; const text = (message: any) => message?.content?.filter((b: any) => b.type === 'text').map((b: any) => b.text).join('') ?? ''; @@ -52,17 +49,15 @@ for (const entry of watch.value.entries) { if (entry.kind === 'pi.assistant') emitted.set(entry.id, text(entry.model?.[0])); } if (globalThis.consoleEnabled) watch.start((event: any) => { if (event.kind === 'value') render(event.value); }); -const stopRequests = await startRequests(harness, context); -const extensions = await loadExtensions(harness, registry, storage, models, context, [CodingTools, CredentialRequests]); const api = harnessApi(harness, models, extensions, context); harness.resume(); await serve(harness, context, globalThis.consoleEnabled ? async () => { await harness.waitForIdle(context); - const final = await root.watch(context); + const final = await conversation.watch(context); render(final.value); await final.stop(); Deno.core.ops.op_output('\n'); -} : undefined, api); +} : undefined, api, async () => (await extensions.standing())!.conversationId); await api.close(); await extensions.close(); await stopRequests(); diff --git a/host/js/messages-test-bundle.js b/host/js/messages-test-bundle.js index 3223328..a5614ae 100644 --- a/host/js/messages-test-bundle.js +++ b/host/js/messages-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base2, fragment) { let node = root2; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base2) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base2) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base2); + const b = this.baseOf(schema4, base2); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base2, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base2, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base2, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base2, next); + next = this.convert(schema4, base2, next); } if (!matched && additional !== void 0) next = this.convert(additional, base2, next); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base2) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base2) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base2); + const b = this.baseOf(schema4, base2); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base2) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base2) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base2) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base2)); + set2(key, this.coerceTypes(value2[key], property, base2)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base2)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base2)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base2)); + set2(key, this.coerceTypes(value2[key], additional, base2)); } return out ?? value2; } - coerceItems(value2, schema, base2) { + coerceItems(value2, schema4, base2) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base2) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base2, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -20108,7 +20108,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool2) => [tool2.name, tool2])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call, tool2, result, truncatio } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool2, result) { - const schema = tool2.structuredOutputSchema; + const schema4 = tool2.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool2.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool2.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28631,6 +28631,6646 @@ var MemoryStorage = class { } }; +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root2) { + const anchors = /* @__PURE__ */ new Set(); + visit(root2, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -29067,7 +35707,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -29192,7 +35832,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -30103,8 +36743,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -30306,11 +36946,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -30527,7 +37167,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -30756,7 +37396,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -30858,8 +37503,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -30965,8 +37610,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -31057,20 +37702,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -31106,9 +37751,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -31116,8 +37761,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -31135,10 +37780,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -31574,7 +38219,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -31582,7 +38227,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -31627,21 +38272,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -31651,12 +38296,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -31799,7 +38444,7 @@ var { SubmissionLanded } = await import(`${base}/lineage/refs.ts`); var { Tally, abstract } = await import(`${base}/lineage/server.ts`); var { normalizeMemoryOp, parseMemoryOps, applyMemoryOps, readMemory, memorizeTask } = await import(`${base}/lineage/memory.ts`); var { Seen, mainOf } = await import(`${base}/lineage/catchup.ts`); -var primaryId = await globalThis.subagentService.standing("ultimate", BACKGROUND_CONTEXT); +var primaryId = await globalThis.subagentService.standing("standing", BACKGROUND_CONTEXT); var primary = await harness.conversation(primaryId, BACKGROUND_CONTEXT); var entries2 = async (conversation) => (await conversation.context(BACKGROUND_CONTEXT)).entries; var replies = async () => (await entries2(primary)).filter((e) => e.kind === "board.reply"); diff --git a/host/js/messages-test.ts b/host/js/messages-test.ts index e886d21..3bf62db 100644 --- a/host/js/messages-test.ts +++ b/host/js/messages-test.ts @@ -59,7 +59,7 @@ const {SubmissionLanded} = await import(`${base}/lineage/refs.ts`); const {Tally, abstract} = await import(`${base}/lineage/server.ts`); const {normalizeMemoryOp, parseMemoryOps, applyMemoryOps, readMemory, memorizeTask} = await import(`${base}/lineage/memory.ts`); const {Seen, mainOf} = await import(`${base}/lineage/catchup.ts`); -const primaryId = await globalThis.subagentService.standing('ultimate', context); +const primaryId = await globalThis.subagentService.standing('standing', context); const primary = (await harness.conversation(primaryId, context))!; const entries = async (conversation: any) => (await conversation.context(context)).entries; const replies = async () => (await entries(primary)).filter((e: any) => e.kind === 'board.reply'); diff --git a/host/js/p3-test-bundle.js b/host/js/p3-test-bundle.js index 108ebbc..43f3c41 100644 --- a/host/js/p3-test-bundle.js +++ b/host/js/p3-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -2301,11 +2301,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -2321,12 +2321,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -2394,8 +2394,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -2471,10 +2471,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -2484,12 +2484,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root, base, fragment) { let node = root; @@ -2576,9 +2576,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -2640,26 +2640,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -2674,7 +2674,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -2683,10 +2683,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -2792,8 +2792,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -2806,7 +2806,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -2816,11 +2816,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -2834,19 +2834,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -2858,9 +2858,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -2874,12 +2874,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -2887,7 +2887,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -2895,31 +2895,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -3015,11 +3015,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -3412,9 +3412,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -3673,9 +3673,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -3741,9 +3741,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -3754,7 +3754,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -4163,9 +4163,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -4517,9 +4517,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -4528,9 +4528,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -4562,18 +4562,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -4631,7 +4631,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -4654,34 +4654,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -4700,12 +4700,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -4714,22 +4714,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -4737,42 +4737,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -4780,7 +4780,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -4789,16 +4789,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -4811,28 +4811,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -4858,7 +4858,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -4886,7 +4886,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -5094,8 +5094,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -8675,10 +8675,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -8719,11 +8719,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -8787,8 +8787,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -8829,15 +8829,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -9341,8 +9341,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -9813,15 +9813,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -10082,8 +10082,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -10194,16 +10194,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -10220,18 +10220,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -10276,13 +10276,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -10291,7 +10291,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -10299,7 +10299,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -10401,15 +10401,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -10775,17 +10775,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -10957,11 +10957,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -12858,10 +12858,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -12888,12 +12888,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -13172,8 +13172,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -13602,11 +13602,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -13854,15 +13854,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry.name, set); + let set2 = this.#subscribers.get(registry.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -15457,19 +15457,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -16228,14 +16228,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -16683,8 +16683,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -16717,8 +16717,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -16736,7 +16736,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -17601,7 +17601,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -17611,15 +17611,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -17630,7 +17630,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -17643,7 +17643,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -17712,7 +17712,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -17720,7 +17720,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -17775,7 +17775,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -17803,9 +17803,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -18436,7 +18436,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -18444,27 +18444,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -19069,7 +19069,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -19077,7 +19077,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20054,21 +20054,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20110,14 +20110,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20144,9 +20144,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20325,12 +20325,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20344,16 +20344,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -22938,20 +22938,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -23859,13 +23859,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24467,18 +24467,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -24658,7 +24658,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -24672,7 +24672,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -27609,16 +27609,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -27626,14 +27626,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -27671,7 +27671,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -27689,7 +27689,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -27759,9 +27759,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28104,16 +28104,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28131,14 +28131,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28156,6 +28156,6646 @@ var MemoryStorage = class { } }; +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -28592,7 +35232,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -28717,7 +35357,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -29628,8 +36268,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -30306,11 +36946,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -30527,7 +37167,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -30756,7 +37396,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -30858,8 +37503,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -30965,8 +37610,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -31057,20 +37702,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -31106,9 +37751,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -31116,8 +37761,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -31135,10 +37780,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -31574,7 +38219,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -31582,7 +38227,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -31627,21 +38272,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -31651,12 +38296,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -31759,10 +38404,10 @@ testReplay(); if (globalThis.p3Mode !== "unit") { const workerId = (transcript) => Number(/Started subagent (\d+)/.exec(JSON.stringify(transcript.messages))?.[1]); const rules = [ - { id: "ultimate-branch", role: "ultimate", match: { kind: "user", text: "launch scenario" }, answer: { tools: [{ name: "branch", args: { repo: "/src/demo", isolated: true, prompt: "begin" } }] } }, - { id: "ultimate-probe", role: "ultimate", match: { kind: "user", text: "launch branch" }, answer: { tools: [{ name: "branch", args: { repo: "/src/demo", prompt: "branch probe" } }] } }, + { id: "standing-branch", role: "standing", match: { kind: "user", text: "launch scenario" }, answer: { tools: [{ name: "branch", args: { repo: "/src/demo", isolated: true, prompt: "begin" } }] } }, + { id: "standing-probe", role: "standing", match: { kind: "user", text: "launch branch" }, answer: { tools: [{ name: "branch", args: { repo: "/src/demo", prompt: "branch probe" } }] } }, { id: "coordinator-probe", role: "coordinator", match: { kind: "user", text: "branch probe" }, answer: { text: "branch complete" } }, - { id: "ultimate-receipt", role: "ultimate", match: { text: "" }, answer: { text: "Receipt noted." } }, + { id: "standing-receipt", role: "standing", match: { text: "" }, answer: { text: "Receipt noted." } }, { id: "coordinator-echo", role: "coordinator", match: { kind: "user", text: "Receipt noted." }, answer: { text: "Acknowledged." } }, { id: "start-worker", role: "coordinator", match: { kind: "user", text: "begin" }, answer: { tools: [{ name: "subagent", args: { action: "start", agent: "worker", isolate: "worktree", task: "build feature", background: true } }] } }, { id: "start-reviewer", role: "coordinator", match: { kind: "user", text: "worker complete" }, answer: { tools: [{ name: "subagent", args: { action: "start", agent: "reviewer", isolate: "none", task: "review feature", background: true } }] } }, @@ -31782,7 +38427,7 @@ if (globalThis.p3Mode !== "unit") { const harness = await Harness.open(storage, { models, registry, settings: { retry: { enabled: false }, get extensions() { return registry.snapshot().installed(); } } }, BACKGROUND_CONTEXT); - const root = await harness.root(BACKGROUND_CONTEXT, { agent: { model: { provider: "faux", modelId: "faux-1" }, instructions: "P3 role:ultimate", cwd: "/src/demo" } }); + const root = await harness.root(BACKGROUND_CONTEXT, { agent: { model: { provider: "faux", modelId: "faux-1" }, instructions: "P3 role:standing", cwd: "/src/demo" } }); if (globalThis.p3Mode === "kill-forward") { const install = registry.install.bind(registry); registry.install = (extension) => install(extension.name !== "workspaces" ? extension : { ...extension, tasks: extension.tasks.map((task) => task.definition.name !== "workspaces.lander" ? task : { definition: { ...task.definition, phases: { ...task.definition.phases, land: async (record2, runtime, ctx) => { @@ -31836,12 +38481,12 @@ if (globalThis.p3Mode !== "unit") { if (globalThis.p3Mode === "load-all") { assert((await root.agent(BACKGROUND_CONTEXT)).tools.some((tool) => tool.name === "branch"), "Every extension must load"); } else { - const ultimate = await harness.conversation(await globalThis.p3Subagents.standing("ultimate", BACKGROUND_CONTEXT), BACKGROUND_CONTEXT); + const standing = await harness.conversation(await globalThis.p3Subagents.standing("standing", BACKGROUND_CONTEXT), BACKGROUND_CONTEXT); harness.resume(); const probe = globalThis.p3Mode.startsWith("branch"); if (globalThis.p3Mode === "branch" || globalThis.p3Mode.startsWith("kill-")) { - await (await ultimate.submit({ type: "input", content: probe ? "launch branch" : "launch scenario", requestId: "p3-launch" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); - const entries3 = (await ultimate.context(BACKGROUND_CONTEXT)).entries; + await (await standing.submit({ type: "input", content: probe ? "launch branch" : "launch scenario", requestId: "p3-launch" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); + const entries3 = (await standing.context(BACKGROUND_CONTEXT)).entries; assert(!JSON.stringify(entries3).includes('"isError":true'), `Branch tool failed: ${JSON.stringify(entries3)}`); } if (globalThis.p3Mode.startsWith("kill-")) await new Promise(() => { @@ -31853,12 +38498,12 @@ if (globalThis.p3Mode !== "unit") { await new Promise((resolve2) => setTimeout(resolve2, 0)); } }; - const replies = async () => (await ultimate.context(BACKGROUND_CONTEXT)).entries.filter((entry2) => entry2.kind === "board.reply"); + const replies = async () => (await standing.context(BACKGROUND_CONTEXT)).entries.filter((entry2) => entry2.kind === "board.reply"); await wait(async () => (await replies()).length > 0, "No branch reply"); const received = await replies(); const coordinator = await harness.conversation(received[0].data.from, BACKGROUND_CONTEXT); - assert((await coordinator.agent(BACKGROUND_CONTEXT)).instructions === "P3 role:coordinator", "Branch must use coordinator definition"); - assert((await conversationChains(harness, BACKGROUND_CONTEXT)(coordinator.id)).includes(String(ultimate.id)), "D63 must include ultimate"); + assert((await coordinator.agent(BACKGROUND_CONTEXT)).instructions.includes("P3 role:coordinator"), "Branch must use coordinator definition"); + assert((await conversationChains(harness, BACKGROUND_CONTEXT)(coordinator.id)).includes(String(standing.id)), "D63 must include standing"); if (!probe) { await wait(async () => Object.keys((await harness.snapshot(globalThis.p3Workspaces.doc, root.id, BACKGROUND_CONTEXT)).results).length === 1, "No landing"); await wait(async () => (await harness.snapshot(globalThis.p3Workspaces.doc, root.id, BACKGROUND_CONTEXT)).queue.length === 0, "Lander did not report"); @@ -31877,9 +38522,9 @@ if (globalThis.p3Mode !== "unit") { assert(!await fs.stat(worker.path).then(() => true, () => false), "Released checkout must not exist"); assert(Object.values(index.results).every((result) => result.outcome === "landed"), `Landing failed: ${JSON.stringify(index)}`); assert((await globalThis.p3Host.eventLog.recent({ events: [{ kind: "event.workspaces.landed" }] })).length === 1, "Expected one landed event"); - const ultimateEntries = (await ultimate.context(BACKGROUND_CONTEXT)).entries; + const standingEntries = (await standing.context(BACKGROUND_CONTEXT)).entries; const landed = Object.values(index.results)[0]; - const cards = ultimateEntries.filter((entry2) => entry2.kind === "board.message" && entry2.data.text.startsWith("[lander] Submission") && entry2.data.text.includes(" landed as ")); + const cards = standingEntries.filter((entry2) => entry2.kind === "board.message" && entry2.data.text.startsWith("[lander] Submission") && entry2.data.text.includes(" landed as ")); assert(cards.length === 1 && cards[0].data.from === coordinator.id && cards[0].data.text.includes(landed.sha), `Expected one landing card through messages: ${JSON.stringify(cards)}`); const repliesNow = await replies(); assert(repliesNow.length === 1 && !repliesNow[0].data.failed && new Set(repliesNow.map((entry2) => entry2.data.id)).size === repliesNow.length, `Duplicate board.reply: ${JSON.stringify(repliesNow)}`); diff --git a/host/js/p3-test.ts b/host/js/p3-test.ts index 76eb64d..c7b441f 100644 --- a/host/js/p3-test.ts +++ b/host/js/p3-test.ts @@ -12,10 +12,10 @@ testReplay(); if (globalThis.p3Mode !== 'unit') { const workerId = (transcript: any) => Number(/Started subagent (\d+)/.exec(JSON.stringify(transcript.messages))?.[1]); const rules: Rule[] = [ - { id: 'ultimate-branch', role: 'ultimate', match: { kind: 'user', text: 'launch scenario' }, answer: { tools: [{ name: 'branch', args: { repo: '/src/demo', isolated: true, prompt: 'begin' } }] } }, - { id: 'ultimate-probe', role: 'ultimate', match: { kind: 'user', text: 'launch branch' }, answer: { tools: [{ name: 'branch', args: { repo: '/src/demo', prompt: 'branch probe' } }] } }, + { id: 'standing-branch', role: 'standing', match: { kind: 'user', text: 'launch scenario' }, answer: { tools: [{ name: 'branch', args: { repo: '/src/demo', isolated: true, prompt: 'begin' } }] } }, + { id: 'standing-probe', role: 'standing', match: { kind: 'user', text: 'launch branch' }, answer: { tools: [{ name: 'branch', args: { repo: '/src/demo', prompt: 'branch probe' } }] } }, { id: 'coordinator-probe', role: 'coordinator', match: { kind: 'user', text: 'branch probe' }, answer: { text: 'branch complete' } }, - { id: 'ultimate-receipt', role: 'ultimate', match: { text: '' }, answer: { text: 'Receipt noted.' } }, + { id: 'standing-receipt', role: 'standing', match: { text: '' }, answer: { text: 'Receipt noted.' } }, { id: 'coordinator-echo', role: 'coordinator', match: { kind: 'user', text: 'Receipt noted.' }, answer: { text: 'Acknowledged.' } }, { id: 'start-worker', role: 'coordinator', match: { kind: 'user', text: 'begin' }, answer: { tools: [{ name: 'subagent', args: { action: 'start', agent: 'worker', isolate: 'worktree', task: 'build feature', background: true } }] } }, { id: 'start-reviewer', role: 'coordinator', match: { kind: 'user', text: 'worker complete' }, answer: { tools: [{ name: 'subagent', args: { action: 'start', agent: 'reviewer', isolate: 'none', task: 'review feature', background: true } }] } }, @@ -32,7 +32,7 @@ if (globalThis.p3Mode !== 'unit') { models.setProvider(scriptedModel(rules, rule => Deno.core.ops.op_output(`scripted rule: ${rule}\n`))); const storage = await openStorage(globalThis.storagePath), registry = createRegistry(); const harness = await Harness.open(storage, { models, registry, settings: { retry: { enabled: false }, get extensions() { return registry.snapshot().installed(); } } }, context); - const root = await harness.root(context, { agent: { model: { provider: 'faux', modelId: 'faux-1' }, instructions: 'P3 role:ultimate', cwd: '/src/demo' } }); + const root = await harness.root(context, { agent: { model: { provider: 'faux', modelId: 'faux-1' }, instructions: 'P3 role:standing', cwd: '/src/demo' } }); // Stop after the durable lander commit records landed.sha, before its event/report commit. if (globalThis.p3Mode === 'kill-forward') { const install = registry.install.bind(registry); @@ -85,12 +85,12 @@ if (globalThis.p3Mode !== 'unit') { if (globalThis.p3Mode === 'load-all') { assert((await root.agent(context)).tools.some((tool: any) => tool.name === 'branch'), 'Every extension must load'); } else { - const ultimate = (await harness.conversation(await globalThis.p3Subagents.standing('ultimate', context), context))!; + const standing = (await harness.conversation(await globalThis.p3Subagents.standing('standing', context), context))!; harness.resume(); const probe = globalThis.p3Mode.startsWith('branch'); if (globalThis.p3Mode === 'branch' || globalThis.p3Mode.startsWith('kill-')) { - await (await ultimate.submit({ type: 'input', content: probe ? 'launch branch' : 'launch scenario', requestId: 'p3-launch' }, context)).wait(context); - const entries = (await ultimate.context(context)).entries; + await (await standing.submit({ type: 'input', content: probe ? 'launch branch' : 'launch scenario', requestId: 'p3-launch' }, context)).wait(context); + const entries = (await standing.context(context)).entries; assert(!JSON.stringify(entries).includes('"isError":true'), `Branch tool failed: ${JSON.stringify(entries)}`); } if (globalThis.p3Mode.startsWith('kill-')) await new Promise(() => {}); @@ -101,12 +101,12 @@ if (globalThis.p3Mode !== 'unit') { await new Promise(resolve => setTimeout(resolve, 0)); } }; - const replies = async () => (await ultimate.context(context)).entries.filter((entry: any) => entry.kind === 'board.reply'); + const replies = async () => (await standing.context(context)).entries.filter((entry: any) => entry.kind === 'board.reply'); await wait(async () => (await replies()).length > 0, 'No branch reply'); const received = await replies(); const coordinator = (await harness.conversation(received[0].data.from, context))!; - assert((await coordinator.agent(context)).instructions === 'P3 role:coordinator', 'Branch must use coordinator definition'); - assert((await conversationChains(harness, context)(coordinator.id)).includes(String(ultimate.id)), 'D63 must include ultimate'); + assert((await coordinator.agent(context)).instructions.includes('P3 role:coordinator'), 'Branch must use coordinator definition'); + assert((await conversationChains(harness, context)(coordinator.id)).includes(String(standing.id)), 'D63 must include standing'); if (!probe) { await wait(async () => Object.keys((await harness.snapshot(globalThis.p3Workspaces.doc, root.id, context)).results).length === 1, 'No landing'); await wait(async () => (await harness.snapshot(globalThis.p3Workspaces.doc, root.id, context)).queue.length === 0, 'Lander did not report'); @@ -125,9 +125,9 @@ if (globalThis.p3Mode !== 'unit') { assert(!await fs.stat(worker.path).then(() => true, () => false), 'Released checkout must not exist'); assert(Object.values(index.results).every((result: any) => result.outcome === 'landed'), `Landing failed: ${JSON.stringify(index)}`); assert((await globalThis.p3Host.eventLog.recent({ events: [{ kind: 'event.workspaces.landed' }] })).length === 1, 'Expected one landed event'); - const ultimateEntries = (await ultimate.context(context)).entries; + const standingEntries = (await standing.context(context)).entries; const landed = Object.values(index.results)[0] as any; - const cards = ultimateEntries.filter((entry: any) => entry.kind === 'board.message' && entry.data.text.startsWith('[lander] Submission') && entry.data.text.includes(' landed as ')); + const cards = standingEntries.filter((entry: any) => entry.kind === 'board.message' && entry.data.text.startsWith('[lander] Submission') && entry.data.text.includes(' landed as ')); assert(cards.length === 1 && cards[0].data.from === coordinator.id && cards[0].data.text.includes(landed.sha), `Expected one landing card through messages: ${JSON.stringify(cards)}`); const repliesNow = await replies(); assert(repliesNow.length === 1 && !repliesNow[0].data.failed && new Set(repliesNow.map((entry: any) => entry.data.id)).size === repliesNow.length, `Duplicate board.reply: ${JSON.stringify(repliesNow)}`); diff --git a/host/js/p4-test-bundle.js b/host/js/p4-test-bundle.js index 0b15db6..b73958c 100644 --- a/host/js/p4-test-bundle.js +++ b/host/js/p4-test-bundle.js @@ -1697,7 +1697,7 @@ trap - EXIT printf 'P4_PHASE_2_OK '`, `set -e -undo list --conversation 1 > /tmp/p4-undo.json +undo list > /tmp/p4-undo.json box ls > /tmp/p4-boxes printf 'P4_PHASE_3_OK '` diff --git a/host/js/p4-test.ts b/host/js/p4-test.ts index ee35cc4..e5c9d70 100644 --- a/host/js/p4-test.ts +++ b/host/js/p4-test.ts @@ -56,7 +56,7 @@ box rm "$id" trap - EXIT printf 'P4_PHASE_2_OK\n'`, `set -e -undo list --conversation 1 > /tmp/p4-undo.json +undo list > /tmp/p4-undo.json box ls > /tmp/p4-boxes printf 'P4_PHASE_3_OK\n'`, ]; diff --git a/host/js/package-lock.json b/host/js/package-lock.json index 137f7f3..bada7ed 100644 --- a/host/js/package-lock.json +++ b/host/js/package-lock.json @@ -7,7 +7,8 @@ "dependencies": { "@earendil-works/chord": "1.5.0", "@earendil-works/pi-ai": "1.5.0", - "@earendil-works/pi-durable": "1.5.0" + "@earendil-works/pi-durable": "1.5.0", + "yaml": "2.9.1" }, "devDependencies": { "esbuild": "0.28.2" @@ -1682,6 +1683,21 @@ "optional": true } } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } } } } diff --git a/host/js/package.json b/host/js/package.json index 47453db..8ce27aa 100644 --- a/host/js/package.json +++ b/host/js/package.json @@ -1,11 +1,16 @@ { "private": true, "type": "module", - "scripts": { "bundle": "nu apply-patch.nu && esbuild main.ts --bundle --format=esm --platform=browser --outfile=bundle.js && esbuild test.ts --bundle --format=esm --platform=browser --outfile=test-bundle.js && esbuild durable-test.ts --bundle --format=esm --platform=browser --outfile=durable-test-bundle.js && esbuild foundation-test.ts --bundle --format=esm --platform=browser --outfile=foundation-test-bundle.js && esbuild extensions-test.ts --bundle --format=esm --platform=browser --outfile=extensions-test-bundle.js && esbuild events-test.ts --bundle --format=esm --platform=browser --outfile=events-test-bundle.js && esbuild subagents-test.ts --bundle --format=esm --platform=browser --outfile=subagents-test-bundle.js && esbuild core-ext-test.ts --bundle --format=esm --platform=browser --outfile=core-ext-test-bundle.js && esbuild plan-todos-test.ts --bundle --format=esm --platform=browser --outfile=plan-todos-test-bundle.js && esbuild p2-test.ts --bundle --format=esm --platform=browser --outfile=p2-test-bundle.js && esbuild chain-test.ts --bundle --format=esm --platform=browser --outfile=chain-test-bundle.js && esbuild undo-harness-test.ts --bundle --format=esm --platform=browser --outfile=undo-harness-test-bundle.js && esbuild messages-test.ts --bundle --format=esm --platform=browser --outfile=messages-test-bundle.js && esbuild p3-test.ts --bundle --format=esm --platform=browser --outfile=p3-test-bundle.js && esbuild automations-test.ts --bundle --format=esm --platform=browser --outfile=automations-test-bundle.js && esbuild watchdog-test.ts --bundle --format=esm --platform=browser --outfile=watchdog-test-bundle.js && esbuild workspaces-test.ts --bundle --format=esm --platform=browser --outfile=workspaces-test-bundle.js && esbuild goal-questions-test.ts --bundle --format=esm --platform=browser --outfile=goal-questions-test-bundle.js && esbuild dream-test.ts --bundle --format=esm --platform=browser --outfile=dream-test-bundle.js && esbuild p4-test.ts --bundle --format=esm --platform=browser --outfile=p4-test-bundle.js && esbuild harness-api-test.ts --bundle --format=esm --platform=browser --outfile=harness-api-test-bundle.js && esbuild proxy-models-test.ts --bundle --format=esm --platform=browser --outfile=proxy-models-test-bundle.js" }, - "dependencies": { - "@earendil-works/pi-durable": "1.5.0", - "@earendil-works/pi-ai": "1.5.0", - "@earendil-works/chord": "1.5.0" + "scripts": { + "bundle": "nu apply-patch.nu && esbuild main.ts --bundle --format=esm --platform=browser --outfile=bundle.js && esbuild test.ts --bundle --format=esm --platform=browser --outfile=test-bundle.js && esbuild durable-test.ts --bundle --format=esm --platform=browser --outfile=durable-test-bundle.js && esbuild foundation-test.ts --bundle --format=esm --platform=browser --outfile=foundation-test-bundle.js && esbuild extensions-test.ts --bundle --format=esm --platform=browser --outfile=extensions-test-bundle.js && esbuild events-test.ts --bundle --format=esm --platform=browser --outfile=events-test-bundle.js && esbuild subagents-test.ts --bundle --format=esm --platform=browser --outfile=subagents-test-bundle.js && esbuild core-ext-test.ts --bundle --format=esm --platform=browser --outfile=core-ext-test-bundle.js && esbuild plan-todos-test.ts --bundle --format=esm --platform=browser --outfile=plan-todos-test-bundle.js && esbuild p2-test.ts --bundle --format=esm --platform=browser --outfile=p2-test-bundle.js && esbuild chain-test.ts --bundle --format=esm --platform=browser --outfile=chain-test-bundle.js && esbuild undo-harness-test.ts --bundle --format=esm --platform=browser --outfile=undo-harness-test-bundle.js && esbuild messages-test.ts --bundle --format=esm --platform=browser --outfile=messages-test-bundle.js && esbuild p3-test.ts --bundle --format=esm --platform=browser --outfile=p3-test-bundle.js && esbuild automations-test.ts --bundle --format=esm --platform=browser --outfile=automations-test-bundle.js && esbuild watchdog-test.ts --bundle --format=esm --platform=browser --outfile=watchdog-test-bundle.js && esbuild workspaces-test.ts --bundle --format=esm --platform=browser --outfile=workspaces-test-bundle.js && esbuild goal-questions-test.ts --bundle --format=esm --platform=browser --outfile=goal-questions-test-bundle.js && esbuild dream-test.ts --bundle --format=esm --platform=browser --outfile=dream-test-bundle.js && esbuild p4-test.ts --bundle --format=esm --platform=browser --outfile=p4-test-bundle.js && esbuild harness-api-test.ts --bundle --format=esm --platform=browser --outfile=harness-api-test-bundle.js && esbuild proxy-models-test.ts --bundle --format=esm --platform=browser --outfile=proxy-models-test-bundle.js" }, - "devDependencies": { "esbuild": "0.28.2" } + "dependencies": { + "@earendil-works/chord": "1.5.0", + "@earendil-works/pi-ai": "1.5.0", + "@earendil-works/pi-durable": "1.5.0", + "yaml": "2.9.1" + }, + "devDependencies": { + "esbuild": "0.28.2" + } } diff --git a/host/js/plan-todos-test-bundle.js b/host/js/plan-todos-test-bundle.js index 3477795..7b2f962 100644 --- a/host/js/plan-todos-test-bundle.js +++ b/host/js/plan-todos-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text2 = contentText(message.content); if (text2.length > 0) content.push(text2); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base2, fragment) { let node = root2; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base2) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base2) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base2); + const b = this.baseOf(schema4, base2); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base2, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base2, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base2, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base2, next); + next = this.convert(schema4, base2, next); } if (!matched && additional !== void 0) next = this.convert(additional, base2, next); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base2) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base2) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base2); + const b = this.baseOf(schema4, base2); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base2) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base2) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base2) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base2)); + set2(key, this.coerceTypes(value2[key], property, base2)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base2)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base2)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base2)); + set2(key, this.coerceTypes(value2[key], additional, base2)); } return out ?? value2; } - coerceItems(value2, schema, base2) { + coerceItems(value2, schema4, base2) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base2) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base2, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add: add2 }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call2, timestamp) { +function missingResult(call2, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call2.id, @@ -20108,7 +20108,7 @@ function missingResult(call2, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text2} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call2, tool, result, truncatio } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call2, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call2, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call2.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28718,8 +28718,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -28825,8 +28825,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -28917,20 +28917,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -28966,9 +28966,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -28976,8 +28976,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -28995,10 +28995,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -29434,7 +29434,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -29442,7 +29442,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -29487,21 +29487,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -29511,12 +29511,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -29571,6 +29571,6646 @@ async function openStorage(path) { return SqliteStorage.open(database); } +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root2) { + const anchors = /* @__PURE__ */ new Set(); + visit(root2, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text2, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text2; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text2.length <= endStep) + return text2; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text2, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text2[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text2[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text2, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text2[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text2[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text2; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text2; + if (onFold) + onFold(); + let res = text2.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text2.length; + if (fold === 0) + res = ` +${indent}${text2.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text2[fold]}\\`; + res += ` +${indent}${text2.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text2, i, indent) { + let end = i; + let start = i + 1; + let ch = text2[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text2[++i]; + } else { + do { + ch = text2[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text2[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add2 = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add2(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add2(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -30007,7 +36647,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -30132,7 +36772,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text2) { +function splitLines2(text2) { const hasTrailingNl = text2.endsWith("\n"); const result = text2.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -31043,8 +37683,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -31246,11 +37886,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -31467,7 +38107,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -31696,7 +38336,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -31851,19 +38496,19 @@ try { assert(Object.keys((await harness.snapshot(Plan, branch.id, BACKGROUND_CONTEXT)).epics).length === 1, "Fork inherited plan"); equal(JSON.parse(text(await call({ action: "show" }, branch.id))), Plan.definition.initial()); assert((await harness.snapshot(Started2, branch.id, BACKGROUND_CONTEXT)).started, "Branch started"); - const ULTIMATE = 5; + const STANDING = 5; const fakeTx = () => { const docs = /* @__PURE__ */ new Map(); return { doc: async ({ definition: def }, id) => { const key = `${def.kind}:${id}`; - if (!docs.has(key)) docs.set(key, def.kind === "ultimate.standing-agents" ? { ultimate: ULTIMATE } : def.initial()); + if (!docs.has(key)) docs.set(key, def.kind === "standing.standing-agents" ? { "$standing": STANDING } : def.initial()); return docs.get(key); } }; }; const list = async (tx) => (await tx.doc(Todos, 1)).items; { const tx = fakeTx(); - equal((await add(tx, " Deploy fleet ", "ultimate")).text, "Deploy fleet"); + equal((await add(tx, " Deploy fleet ", "standing")).text, "Deploy fleet"); assert((await add(tx, "Rotate the key", "user")).id === 2, "Sequential todo ids"); await rejects(() => add(tx, " ", "user"), "nonempty"); await rejects(() => add(tx, "x", "lander"), "owner"); @@ -31871,7 +38516,7 @@ try { } { const tx = fakeTx(); - for (let i = 0; i < DONE_LIMIT + 2; i++) await add(tx, `t${i}`, "ultimate"); + for (let i = 0; i < DONE_LIMIT + 2; i++) await add(tx, `t${i}`, "standing"); assert(typeof (await mark(tx, 1, true)).done === "number", "Tick"); assert((await mark(tx, 1, false)).done === void 0, "Reopen"); for (const todo of (await list(tx)).slice(0, -1)) todo.done = todo.id; @@ -31880,9 +38525,9 @@ try { await rejects(() => mark(tx, 999, true), "No to-do 999"); } { - const tx = fakeTx(), content = async () => (await noteFor(tx, ULTIMATE, 0))?.entries[0].model[0].content; + const tx = fakeTx(), content = async () => (await noteFor(tx, STANDING, 0))?.entries[0].model[0].content; assert(await content() === void 0, "Empty note"); - await add(tx, "Mine", "ultimate"); + await add(tx, "Mine", "standing"); await add(tx, "Theirs", "user"); equal(await content(), "Open to-dos (todo tool: done when finished):\nYours:\n- 1: Mine\nThe user's:\n- 2: Theirs"); assert(await content() === void 0, "Unchanged note"); @@ -31894,17 +38539,17 @@ try { { const tx = fakeTx(), extension2 = todosModule.default(), tool2 = extension2.tools[0]; const run2 = (conversationId, args) => tool2.execute(args, { conversationId, commit: (fn) => fn(tx) }, BACKGROUND_CONTEXT); - await rejects(() => run2(9, { action: "list" }), "Only @ultimate"); - equal(await run2(ULTIMATE, { action: "add", text: "Ship it", owner: "user" }), { output: [{ type: "text", text: "Added 1 for user: Ship it" }] }); - equal(await run2(ULTIMATE, { action: "list" }), { output: [{ type: "text", text: "The user's:\n- 1: Ship it" }] }); + await rejects(() => run2(9, { action: "list" }), "Only the standing agent"); + equal(await run2(STANDING, { action: "add", text: "Ship it", owner: "user" }), { output: [{ type: "text", text: "Added 1 for user: Ship it" }] }); + equal(await run2(STANDING, { action: "list" }), { output: [{ type: "text", text: "The user's:\n- 1: Ship it" }] }); const before = (conversationId) => extension2.hooks[0].handlers.beforeInput({}, { tx, conversationId }, BACKGROUND_CONTEXT); assert(await before(9) === void 0, "Nonstanding note"); - assert(await before(ULTIMATE) !== void 0, "Standing note"); + assert(await before(STANDING) !== void 0, "Standing note"); } await harness.commit(async (tx) => { - (await tx.doc(Standing, root.id)).ultimate = root.id; + (await tx.doc(Standing, root.id))["$standing"] = root.id; }, BACKGROUND_CONTEXT); - assert(text(await call({ action: "add", text: "Real world", owner: "ultimate" }, root.id, "todo")).includes("Added 1"), "Loaded todo tool"); + assert(text(await call({ action: "add", text: "Real world", owner: "standing" }, root.id, "todo")).includes("Added 1"), "Loaded todo tool"); assert(text(await call({ action: "list" }, root.id, "todo")).includes("Real world"), "Loaded todo list"); assert((await root.context(BACKGROUND_CONTEXT)).entries.some((entry2) => entry2.kind === "todos.note"), "Real beforeInput note"); await fs.write("/saved", JSON.stringify({ plan: await harness.snapshot(Plan, root.id, BACKGROUND_CONTEXT), index: await harness.snapshot(TaskIndex, root.id, BACKGROUND_CONTEXT), todos: await harness.snapshot(Todos, root.id, BACKGROUND_CONTEXT) })); diff --git a/host/js/plan-todos-test.ts b/host/js/plan-todos-test.ts index b98800a..8ab8e56 100644 --- a/host/js/plan-todos-test.ts +++ b/host/js/plan-todos-test.ts @@ -1,4 +1,4 @@ -/** The six Ultimate plan/todos cases, plus real-loader turns and branch reset. */ +/** The six Standing agent plan/todos cases, plus real-loader turns and branch reset. */ import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context'; import { createModels } from '@earendil-works/pi-ai/models'; import { fauxProvider, fauxAssistantMessage, fauxToolCall } from '@earendil-works/pi-ai/providers/faux'; @@ -113,37 +113,37 @@ try { assert((await harness.snapshot(Started,branch.id,context)).started,'Branch started'); // Todos cases 1-4 retain the original small transaction fixture. - const ULTIMATE=5; - const fakeTx=()=>{const docs=new Map();return {doc:async({definition:def}:any,id:number)=>{const key=`${def.kind}:${id}`;if(!docs.has(key))docs.set(key,def.kind==='ultimate.standing-agents'?{ultimate:ULTIMATE}:def.initial());return docs.get(key);}};}; + const STANDING=5; + const fakeTx=()=>{const docs=new Map();return {doc:async({definition:def}:any,id:number)=>{const key=`${def.kind}:${id}`;if(!docs.has(key))docs.set(key,def.kind==='standing.standing-agents'?{'$standing':STANDING}:def.initial());return docs.get(key);}};}; const list=async(tx:any)=>(await tx.doc(Todos,1)).items; { - const tx=fakeTx();equal((await add(tx,' Deploy fleet ','ultimate')).text,'Deploy fleet'); + const tx=fakeTx();equal((await add(tx,' Deploy fleet ','standing')).text,'Deploy fleet'); assert((await add(tx,'Rotate the key','user')).id===2,'Sequential todo ids'); await rejects(()=>add(tx,' ','user'),'nonempty');await rejects(()=>add(tx,'x','lander'),'owner');equal((await list(tx)).map((todo:any)=>todo.id),[1,2]); } { - const tx=fakeTx();for(let i=0;itodo.id),Array.from({length:DONE_LIMIT},(_,i)=>i+3));await rejects(()=>mark(tx,999,true),'No to-do 999'); } { - const tx=fakeTx(), content=async()=>(await noteFor(tx,ULTIMATE,0))?.entries[0].model[0].content; - assert(await content()===undefined,'Empty note');await add(tx,'Mine','ultimate');await add(tx,'Theirs','user'); + const tx=fakeTx(), content=async()=>(await noteFor(tx,STANDING,0))?.entries[0].model[0].content; + assert(await content()===undefined,'Empty note');await add(tx,'Mine','standing');await add(tx,'Theirs','user'); equal(await content(),"Open to-dos (todo tool: done when finished):\nYours:\n- 1: Mine\nThe user's:\n- 2: Theirs");assert(await content()===undefined,'Unchanged note'); await mark(tx,1,true);await mark(tx,2,true);equal(await content(),'No to-dos are open.');assert(await content()===undefined,'Unchanged empty note'); } { const tx=fakeTx(), extension=todosModule.default(), tool=extension.tools[0]; const run=(conversationId:number,args:any)=>tool.execute(args,{conversationId,commit:(fn:any)=>fn(tx)},context); - await rejects(()=>run(9,{action:'list'}),'Only @ultimate');equal(await run(ULTIMATE,{action:'add',text:'Ship it',owner:'user'}),{output:[{type:'text',text:'Added 1 for user: Ship it'}]}); - equal(await run(ULTIMATE,{action:'list'}),{output:[{type:'text',text:"The user's:\n- 1: Ship it"}]}); + await rejects(()=>run(9,{action:'list'}),'Only the standing agent');equal(await run(STANDING,{action:'add',text:'Ship it',owner:'user'}),{output:[{type:'text',text:'Added 1 for user: Ship it'}]}); + equal(await run(STANDING,{action:'list'}),{output:[{type:'text',text:"The user's:\n- 1: Ship it"}]}); const before=(conversationId:number)=>extension.hooks[0].handlers.beforeInput({}, {tx,conversationId},context); - assert(await before(9)===undefined,'Nonstanding note');assert(await before(ULTIMATE)!==undefined,'Standing note'); + assert(await before(9)===undefined,'Nonstanding note');assert(await before(STANDING)!==undefined,'Standing note'); } // The real world also calls todo through the loaded factory and places its note. - await harness.commit(async(tx:any)=>{(await tx.doc(Standing,root.id)).ultimate=root.id;},context); - assert(text(await call({action:'add',text:'Real world',owner:'ultimate'},root.id,'todo')).includes('Added 1'),'Loaded todo tool'); + await harness.commit(async(tx:any)=>{(await tx.doc(Standing,root.id))['$standing']=root.id;},context); + assert(text(await call({action:'add',text:'Real world',owner:'standing'},root.id,'todo')).includes('Added 1'),'Loaded todo tool'); assert(text(await call({action:'list'},root.id,'todo')).includes('Real world'),'Loaded todo list'); assert((await root.context(context)).entries.some((entry:any)=>entry.kind==='todos.note'),'Real beforeInput note'); await fs.write('/saved',JSON.stringify({plan:await harness.snapshot(Plan,root.id,context),index:await harness.snapshot(TaskIndex,root.id,context),todos:await harness.snapshot(Todos,root.id,context)})); diff --git a/host/js/proxy-models-test-bundle.js b/host/js/proxy-models-test-bundle.js index 9ac2b56..da4b2bc 100644 --- a/host/js/proxy-models-test-bundle.js +++ b/host/js/proxy-models-test-bundle.js @@ -160,7 +160,7 @@ var init_event_stream = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -177,7 +177,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -260,13 +260,13 @@ function defaultProviderAuthContext() { }, async fileExists(path4) { try { - const fs2 = await importNodeModule("node:fs/promises"); + const fs3 = await importNodeModule("node:fs/promises"); let resolved = path4; if (resolved.startsWith("~")) { const os2 = await importNodeModule("node:os"); resolved = os2.homedir() + resolved.slice(1); } - await fs2.access(resolved); + await fs3.access(resolved); return true; } catch { return false; @@ -568,8 +568,8 @@ var init_models_store = __esm({ // node_modules/@earendil-works/pi-telemetry/dist/metrics.js function createTypedMetrics(metrics, schemas) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -631,8 +631,8 @@ var init_memory = __esm({ }); // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -1069,11 +1069,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1085,14 +1085,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function collapseSystemMessages(context) { @@ -1725,11 +1725,11 @@ var init_models = __esm({ if (!resolution) { throw new ModelsError("auth", `Provider is not configured: ${model2.provider}`); } - const auth = resolution.auth; - const apiKey = options?.apiKey ?? auth.apiKey; - const requestModel = auth.baseUrl ? { ...model2, baseUrl: auth.baseUrl } : model2; + const auth2 = resolution.auth; + const apiKey = options?.apiKey ?? auth2.apiKey; + const requestModel = auth2.baseUrl ? { ...model2, baseUrl: auth2.baseUrl } : model2; const sessionId = options && "sessionId" in options && typeof options.sessionId === "string" ? options.sessionId : void 0; - let headers = mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel, sessionId), auth.headers), options?.headers); + let headers = mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel, sessionId), auth2.headers), options?.headers); if (options?.transformHeaders) headers = await options.transformHeaders(headers ?? {}); const env = resolution.env || options?.env ? { ...resolution.env ?? {}, ...options?.env ?? {} } : void 0; @@ -2489,18 +2489,18 @@ function maybeObj(x) { } return x ?? {}; } -function isEmptyObj(obj) { - if (!obj) +function isEmptyObj(obj2) { + if (!obj2) return true; - for (const _k in obj) + for (const _k in obj2) return false; return true; } -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); +function hasOwn(obj2, key) { + return Object.prototype.hasOwnProperty.call(obj2, key); } -function isObj(obj) { - return obj != null && typeof obj === "object" && !Array.isArray(obj); +function isObj(obj2) { + return obj2 != null && typeof obj2 === "object" && !Array.isArray(obj2); } var startsWithSchemeRegexp, isAbsoluteURL, isArray, isReadonlyArray, validatePositiveInteger, safeJSON; var init_values = __esm({ @@ -2739,13 +2739,13 @@ var init_shims = __esm({ }); // node_modules/openai/internal/utils/bytes.mjs -function encodeUTF8(str) { - let encoder; - return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str); +function encodeUTF8(str2) { + let encoder3; + return (encodeUTF8_ ?? (encoder3 = new globalThis.TextEncoder(), encodeUTF8_ = encoder3.encode.bind(encoder3)))(str2); } -function decodeUTF8(bytes) { - let decoder; - return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes); +function decodeUTF8(bytes2) { + let decoder3; + return (decodeUTF8_ ?? (decoder3 = new globalThis.TextDecoder(), decodeUTF8_ = decoder3.decode.bind(decoder3)))(bytes2); } var encodeUTF8_, decodeUTF8_; var init_bytes = __esm({ @@ -3315,12 +3315,12 @@ async function* iterSSEChunks(iterator) { yield data.slice(dataStart, dataEnd); } } -function partition(str, delimiter) { - const index = str.indexOf(delimiter); +function partition(str2, delimiter) { + const index = str2.indexOf(delimiter); if (index !== -1) { - return [str.slice(0, index), delimiter, str.slice(index + delimiter.length)]; + return [str2.slice(0, index), delimiter, str2.slice(index + delimiter.length)]; } - return [str, "", ""]; + return [str2, "", ""]; } var _Stream_instances, _Stream_client, _Stream_isTeeBranch, _Stream_cancelIterator, Stream, DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES, SSEDecoder; var init_streaming = __esm({ @@ -3575,8 +3575,8 @@ var init_streaming = __esm({ if (done) { return ctrl.close(); } - const bytes = encodeUTF8(JSON.stringify(value) + "\n"); - ctrl.enqueue(bytes); + const bytes2 = encodeUTF8(JSON.stringify(value) + "\n"); + ctrl.enqueue(bytes2); } catch (err) { ctrl.error(err); void cancel().catch(() => void 0); @@ -3939,11 +3939,11 @@ var init_formats = __esm({ }); // node_modules/openai/internal/qs/utils.mjs -function is_buffer(obj) { - if (!obj || typeof obj !== "object") { +function is_buffer(obj2) { + if (!obj2 || typeof obj2 !== "object") { return false; } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + return !!(obj2.constructor && obj2.constructor.isBuffer && obj2.constructor.isBuffer(obj2)); } function maybe_map(val, fn) { if (isArray(val)) { @@ -3960,10 +3960,10 @@ var init_utils = __esm({ "node_modules/openai/internal/qs/utils.mjs"() { init_formats(); init_values(); - has = (obj, key) => { + has = (obj2, key) => { const resolvedHas = cachedHas ?? Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty); cachedHas = resolvedHas; - return resolvedHas(obj, key); + return resolvedHas(obj2, key); }; hex_table = /* @__PURE__ */ (() => { const array = []; @@ -3973,27 +3973,27 @@ var init_utils = __esm({ return array; })(); limit = 1024; - encode = (str, _defaultEncoder, charset, _kind, format) => { - if (str.length === 0) { - return str; + encode = (str2, _defaultEncoder, charset, _kind, format) => { + if (str2.length === 0) { + return str2; } - let string = str; - if (typeof str === "symbol") { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string = String(str); + let string2 = str2; + if (typeof str2 === "symbol") { + string2 = Symbol.prototype.toString.call(str2); + } else if (typeof str2 !== "string") { + string2 = String(str2); } if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, ($0) => "%26%23" + Number.parseInt($0.slice(2), 16) + "%3B"); + return escape(string2).replace(/%u[0-9a-f]{4}/gi, ($0) => "%26%23" + Number.parseInt($0.slice(2), 16) + "%3B"); } let out = ""; - for (let j = 0; j < string.length; ) { - let segmentEnd = Math.min((Math.floor(j / limit) + 1) * limit, string.length); - if (segmentEnd < string.length && string.codePointAt(segmentEnd - 1) > 65535) { + for (let j = 0; j < string2.length; ) { + let segmentEnd = Math.min((Math.floor(j / limit) + 1) * limit, string2.length); + if (segmentEnd < string2.length && string2.codePointAt(segmentEnd - 1) > 65535) { segmentEnd += 1; } - const segment = string.length >= limit ? string.slice(j, segmentEnd) : string; - const arr = []; + const segment = string2.length >= limit ? string2.slice(j, segmentEnd) : string2; + const arr2 = []; for (let i = 0; i < segment.length; ++i) { let c = segment.charCodeAt(i); if (c === 45 || // - @@ -4004,26 +4004,26 @@ var init_utils = __esm({ c >= 65 && c <= 90 || // a-z c >= 97 && c <= 122 || // A-Z format === RFC1738 && (c === 40 || c === 41)) { - arr[arr.length] = segment.charAt(i); + arr2[arr2.length] = segment.charAt(i); continue; } if (c < 128) { - arr[arr.length] = hex_table[c]; + arr2[arr2.length] = hex_table[c]; continue; } if (c < 2048) { - arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + arr2[arr2.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; continue; } if (c < 55296 || c >= 57344) { - arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + arr2[arr2.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; continue; } i += 1; c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); - arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + arr2[arr2.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; } - out += arr.join(""); + out += arr2.join(""); j = segmentEnd; } return out; @@ -4035,8 +4035,8 @@ var init_utils = __esm({ function is_non_nullish_primitive(v) { return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; } -function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder3, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj2 = object; let tmp_sc = sideChannel; let step = 0; let find_flag = false; @@ -4055,74 +4055,74 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al } } if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === "comma" && isArray(obj)) { - obj = maybe_map(obj, (value) => { + obj2 = filter(prefix, obj2); + } else if (obj2 instanceof Date) { + obj2 = serializeDate?.(obj2); + } else if (generateArrayPrefix === "comma" && isArray(obj2)) { + obj2 = maybe_map(obj2, (value) => { if (value instanceof Date) { return serializeDate?.(value); } return value; }); } - if (obj === null) { + if (obj2 === null) { if (strictNullHandling) { - return encoder && !encodeValuesOnly ? ( + return encoder3 && !encodeValuesOnly ? ( // @ts-expect-error - encoder(prefix, defaults.encoder, charset, "key", format) + encoder3(prefix, defaults.encoder, charset, "key", format) ) : prefix; } - obj = ""; + obj2 = ""; } - if (is_non_nullish_primitive(obj) || is_buffer(obj)) { - if (encoder) { + if (is_non_nullish_primitive(obj2) || is_buffer(obj2)) { + if (encoder3) { const key_value = encodeValuesOnly ? prefix : ( // @ts-expect-error - encoder(prefix, defaults.encoder, charset, "key", format) + encoder3(prefix, defaults.encoder, charset, "key", format) ); return [ formatter?.(key_value) + "=" + // @ts-expect-error - formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) + formatter?.(encoder3(obj2, defaults.encoder, charset, "value", format)) ]; } - return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + return [formatter?.(prefix) + "=" + formatter?.(String(obj2))]; } const values = []; - if (obj === void 0) { + if (obj2 === void 0) { return values; } let obj_keys; - if (generateArrayPrefix === "comma" && isArray(obj)) { - if (encodeValuesOnly && encoder) { - obj = maybe_map(obj, encoder); + if (generateArrayPrefix === "comma" && isArray(obj2)) { + if (encodeValuesOnly && encoder3) { + obj2 = maybe_map(obj2, encoder3); } - obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + obj_keys = [{ value: obj2.length > 0 ? obj2.join(",") || null : void 0 }]; } else if (isArray(filter)) { obj_keys = filter; } else { - const keys = Object.keys(obj); + const keys = Object.keys(obj2); if (sort) { keys.sort(sort); } obj_keys = keys; } const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; - if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + const adjusted_prefix = commaRoundTrip && isArray(obj2) && obj2.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj2) && obj2.length === 0) { return adjusted_prefix + "[]"; } for (const key of obj_keys) { const value = ( // @ts-ignore - typeof key === "object" && key.value !== void 0 ? key.value : obj[key] + typeof key === "object" && key.value !== void 0 ? key.value : obj2[key] ); if (skipNulls && value === null) { continue; } const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; let key_prefix; - if (isArray(obj)) { + if (isArray(obj2)) { key_prefix = typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix; } else { key_prefix = adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); @@ -4139,7 +4139,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al skipNulls, encodeDotInKeys, // @ts-ignore - generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, + generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj2) ? null : encoder3, filter, sort, allowDots, @@ -4221,36 +4221,36 @@ function normalize_stringify_options(opts = defaults) { }; } function stringify(object, opts = {}) { - let obj = object; + let obj2 = object; const options = normalize_stringify_options(opts); let obj_keys; let filter; if (typeof options.filter === "function") { filter = options.filter; - obj = filter("", obj); + obj2 = filter("", obj2); } else if (isArray(options.filter)) { filter = options.filter; obj_keys = filter; } const keys = []; - if (typeof obj !== "object" || obj === null) { + if (typeof obj2 !== "object" || obj2 === null) { return ""; } const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; if (!obj_keys) { - obj_keys = Object.keys(obj); + obj_keys = Object.keys(obj2); } if (options.sort) { obj_keys.sort(options.sort); } const sideChannel = /* @__PURE__ */ new WeakMap(); for (const key of obj_keys) { - if (options.skipNulls && obj[key] === null) { + if (options.skipNulls && obj2[key] === null) { continue; } push_to_array(keys, inner_stringify( - obj[key], + obj2[key], key, // @ts-expect-error generateArrayPrefix, @@ -4302,8 +4302,8 @@ var init_stringify = __esm({ return String(prefix); } }; - push_to_array = function push_to_array2(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); + push_to_array = function push_to_array2(arr2, value_or_array) { + Array.prototype.push.apply(arr2, isArray(value_or_array) ? value_or_array : [value_or_array]); }; defaults = { addQueryPrefix: false, @@ -4679,7 +4679,7 @@ function decodeNativeResponseBody(body) { return new TextDecoder("utf-8", { ignoreBOM: typeof scope.Bun?.version === "string" }).decode(body); } async function parseOAuthTokenResponse(response) { - let readText; + let readText2; let responsePrototype = null; for (let depth = 0, prototype = response; prototype !== null && depth < 16; prototype = Object.getPrototypeOf(prototype), depth += 1) { if (prototype === NATIVE_RESPONSE_PROTOTYPE) { @@ -4697,12 +4697,12 @@ async function parseOAuthTokenResponse(response) { } const bodyReader = Object.getOwnPropertyDescriptor(prototype, "text")?.value; if (typeof bodyReader === "function" && isResponseBodyPrototype(prototype, responsePrototype)) { - readText = bodyReader; + readText2 = bodyReader; break; } return parser.value.call(response); } - const body = readText === void 0 ? decodeNativeResponseBody(await READ_NATIVE_RESPONSE_BODY.call(response)) : await readText.call(response); + const body = readText2 === void 0 ? decodeNativeResponseBody(await READ_NATIVE_RESPONSE_BODY.call(response)) : await readText2.call(response); try { return JSON.parse(body); } catch { @@ -5070,8 +5070,8 @@ var init_x509_transport_registry = __esm({ // node_modules/openai/internal/auth/x509-workload-identity-auth.mjs function assertSafeHeaders(headers) { for (const name of Headers.prototype.keys.call(headers)) { - const canonical = name.toLowerCase().split("_").join("-"); - if (canonical !== "authorization" && isSensitiveHeader(canonical) || canonical === "host") { + const canonical2 = name.toLowerCase().split("_").join("-"); + if (canonical2 !== "authorization" && isSensitiveHeader(canonical2) || canonical2 === "host") { throw new OpenAIError("X.509 workload identity cannot send conflicting authentication credentials."); } } @@ -5739,11 +5739,11 @@ var init_x509_workload_identity_auth = __esm({ throw new OpenAIError("X.509 workload identity cannot omit its enrolled organization or project."); } for (const name of supplied.values.keys()) { - const canonical = name.toLowerCase().split("_").join("-"); - if ((canonical === "openai-organization" || canonical === "openai-project") && (name !== canonical || headerValue(supplied.values, name) !== (canonical === "openai-organization" ? context.organization : context.project))) { + const canonical2 = name.toLowerCase().split("_").join("-"); + if ((canonical2 === "openai-organization" || canonical2 === "openai-project") && (name !== canonical2 || headerValue(supplied.values, name) !== (canonical2 === "openai-organization" ? context.organization : context.project))) { throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project."); } - if (isSensitiveHeader(canonical) || canonical === "host") { + if (isSensitiveHeader(canonical2) || canonical2 === "host") { throw new OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials."); } } @@ -5758,8 +5758,8 @@ var init_x509_workload_identity_auth = __esm({ throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project."); } for (const name of Headers.prototype.keys.call(headers)) { - const canonical = name.toLowerCase().split("_").join("-"); - if ((canonical === "openai-organization" || canonical === "openai-project") && name !== canonical) { + const canonical2 = name.toLowerCase().split("_").join("-"); + if ((canonical2 === "openai-organization" || canonical2 === "openai-project") && name !== canonical2) { throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project."); } } @@ -6316,8 +6316,8 @@ var init_resource = __esm({ }); // node_modules/openai/internal/utils/path.mjs -function encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +function encodeURIPath(str2) { + return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } var EMPTY, createPathTagFunction, path; var init_path = __esm({ @@ -6624,14 +6624,14 @@ function getTrustedForeignIntrinsic(prototype) { function isTrustedIntrinsicPrototype(prototype) { return trustedIntrinsicPrototypes.has(prototype) || getTrustedForeignIntrinsic(prototype) !== void 0; } -function isCanonicalIntrinsicFunction(value, canonical, functionPrototype) { - if (canonical === void 0) { +function isCanonicalIntrinsicFunction(value, canonical2, functionPrototype) { + if (canonical2 === void 0) { return value === void 0; } - if (typeof value !== "function" || typeof canonical !== "function") { + if (typeof value !== "function" || typeof canonical2 !== "function") { return false; } - const source = functionToString.call(canonical); + const source = functionToString.call(canonical2); if (functionToString.call(value) !== source) { return false; } @@ -6645,23 +6645,23 @@ function isCanonicalIntrinsicFunction(value, canonical, functionPrototype) { const intrinsic = getTrustedForeignIntrinsic(actualFunctionPrototype); return intrinsic !== void 0 && functionToString.call(intrinsic.constructor) === nativeFunctionConstructorSource; } -function isCanonicalIntrinsicDescriptor(descriptor, canonical, functionPrototype) { - if (!canonical || descriptor.configurable !== canonical.configurable || descriptor.enumerable !== canonical.enumerable || "value" in descriptor !== "value" in canonical) { +function isCanonicalIntrinsicDescriptor(descriptor, canonical2, functionPrototype) { + if (!canonical2 || descriptor.configurable !== canonical2.configurable || descriptor.enumerable !== canonical2.enumerable || "value" in descriptor !== "value" in canonical2) { return false; } - if ("value" in descriptor && "value" in canonical) { - if (descriptor.writable !== canonical.writable) { + if ("value" in descriptor && "value" in canonical2) { + if (descriptor.writable !== canonical2.writable) { return false; } - if (typeof canonical.value === "function") { - return isCanonicalIntrinsicFunction(descriptor.value, canonical.value, functionPrototype); + if (typeof canonical2.value === "function") { + return isCanonicalIntrinsicFunction(descriptor.value, canonical2.value, functionPrototype); } - if (canonical.value !== null && typeof canonical.value === "object") { + if (canonical2.value !== null && typeof canonical2.value === "object") { return false; } - return Object.is(descriptor.value, canonical.value); + return Object.is(descriptor.value, canonical2.value); } - return isCanonicalIntrinsicFunction(descriptor.get, canonical.get, functionPrototype) && isCanonicalIntrinsicFunction(descriptor.set, canonical.set, functionPrototype); + return isCanonicalIntrinsicFunction(descriptor.get, canonical2.get, functionPrototype) && isCanonicalIntrinsicFunction(descriptor.set, canonical2.set, functionPrototype); } function hasNativeErrorBrand(current) { if (nativeErrorBrand) { @@ -6710,11 +6710,11 @@ function isTrustedNativeErrorStack(current, descriptor) { } let canonicalDescriptor = foreignErrorStackDescriptors.get(verified.prototype); if (!canonicalDescriptor) { - const canonical = Reflect.construct(verified.constructor, []); - if (typeof canonical !== "object" || canonical === null || !hasNativeErrorBrand(canonical) || Object.getPrototypeOf(canonical) !== verified.prototype) { + const canonical2 = Reflect.construct(verified.constructor, []); + if (typeof canonical2 !== "object" || canonical2 === null || !hasNativeErrorBrand(canonical2) || Object.getPrototypeOf(canonical2) !== verified.prototype) { return false; } - canonicalDescriptor = Object.getOwnPropertyDescriptor(canonical, "stack"); + canonicalDescriptor = Object.getOwnPropertyDescriptor(canonical2, "stack"); if (!canonicalDescriptor || "value" in canonicalDescriptor || typeof canonicalDescriptor.get !== "function" || typeof canonicalDescriptor.set !== "function") { return false; } @@ -6774,7 +6774,7 @@ function getRetainedStorageBrand(current) { } return void 0; } -function estimateRetainedBufferBytes(current, visit, depth) { +function estimateRetainedBufferBytes(current, visit3, depth) { if (ArrayBuffer.isView(current)) { let buffer; let kind2 = "typed-array"; @@ -6787,7 +6787,7 @@ function estimateRetainedBufferBytes(current, visit, depth) { if (typeof buffer !== "object" || buffer === null) { return { bytes: Number.POSITIVE_INFINITY, kind: kind2 }; } - visit(buffer, depth + 1); + visit3(buffer, depth + 1); return { bytes: 0, kind: kind2 }; } const brand = getRetainedStorageBrand(current); @@ -6826,23 +6826,23 @@ function estimateRetainedBufferBytes(current, visit, depth) { return void 0; } } - const bytes = getter?.call(current); + const bytes2 = getter?.call(current); return { - bytes: typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 ? bytes : Number.POSITIVE_INFINITY, + bytes: typeof bytes2 === "number" && Number.isSafeInteger(bytes2) && bytes2 >= 0 ? bytes2 : Number.POSITIVE_INFINITY, kind }; } -function visitHiddenEventValues(current, kind, visit) { +function visitHiddenEventValues(current, kind, visit3) { if (kind === "map") { for (const [key, entry] of mapEntries.call(current)) { - if (!visit(key, 8) || !visit(entry, 8)) { + if (!visit3(key, 8) || !visit3(entry, 8)) { return false; } } } if (kind === "set") { for (const entry of setValues.call(current)) { - if (!visit(entry, 8)) { + if (!visit3(entry, 8)) { return false; } } @@ -6852,7 +6852,7 @@ function visitHiddenEventValues(current, kind, visit) { return false; } for (const [name, value] of headersEntries.call(current)) { - if (!visit(name, 8) || !visit(value, 8)) { + if (!visit3(name, 8) || !visit3(value, 8)) { return false; } } @@ -6882,7 +6882,7 @@ function getInspectableEventKeys(current, kind, availableBytes) { return !Number.isInteger(index) || index < 0 || index >= length || String(index) !== key; }); } -function visitInspectableEventProperties(current, kind, depth, availableBytes, charge, visit) { +function visitInspectableEventProperties(current, kind, depth, availableBytes, charge, visit3) { const keys = getInspectableEventKeys(current, kind, availableBytes()); if (keys === void 0) { return false; @@ -6892,7 +6892,7 @@ function visitInspectableEventProperties(current, kind, depth, availableBytes, c return false; } if (typeof key === "symbol") { - visit(key, depth + 1); + visit3(key, depth + 1); } const descriptor = Object.getOwnPropertyDescriptor(current, key); if (!descriptor) { @@ -6904,11 +6904,11 @@ function visitInspectableEventProperties(current, kind, depth, availableBytes, c } return false; } - visit(descriptor.value, depth + 1, kind === "blob"); + visit3(descriptor.value, depth + 1, kind === "blob"); } return true; } -function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit, retainPrototype) { +function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit3, retainPrototype) { let prototype = Object.getPrototypeOf(current); for (let prototypeDepth = depth + 1; prototype !== null; prototypeDepth += 1) { if (prototypeDepth >= MAX_BUFFERED_EVENT_DEPTH) { @@ -6918,7 +6918,7 @@ function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visi return true; } if (visited.has(prototype)) { - visit(prototype, prototypeDepth); + visit3(prototype, prototypeDepth); return availableBytes() >= 0; } visited.add(prototype); @@ -6929,7 +6929,7 @@ function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visi } const intrinsic = getTrustedForeignIntrinsic(retainedPrototype); if (!intrinsic) { - return visitInspectableEventProperties(retainedPrototype, void 0, prototypeDepth, availableBytes, charge, visit); + return visitInspectableEventProperties(retainedPrototype, void 0, prototypeDepth, availableBytes, charge, visit3); } for (const key of Reflect.ownKeys(retainedPrototype)) { const descriptor = Object.getOwnPropertyDescriptor(retainedPrototype, key); @@ -6943,9 +6943,9 @@ function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visi return false; } if (typeof key === "symbol") { - visit(key, prototypeDepth + 1); + visit3(key, prototypeDepth + 1); } - visit(descriptor.value, prototypeDepth + 1); + visit3(descriptor.value, prototypeDepth + 1); } return availableBytes() >= 0; }); @@ -6957,26 +6957,26 @@ function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visi return true; } function inspectBufferedEventGraph(value, remainingBytes) { - let bytes = 0; + let bytes2 = 0; let scalarBytes = 0; const visited = /* @__PURE__ */ new WeakSet(); const visitedSymbols = /* @__PURE__ */ new Set(); const roots = /* @__PURE__ */ new Set(); const nodes = /* @__PURE__ */ new Map(); let activeNode; - const availableBytes = () => remainingBytes - bytes; + const availableBytes = () => remainingBytes - bytes2; const charge = (amount) => { if (!Number.isSafeInteger(amount) || amount < 0) { - bytes = remainingBytes + 1; + bytes2 = remainingBytes + 1; return false; } - bytes += amount; + bytes2 += amount; if (activeNode) { activeNode.bytes += amount; } else { scalarBytes += amount; } - return bytes <= remainingBytes; + return bytes2 <= remainingBytes; }; const addIdentity = (identity) => { if (activeNode) { @@ -7011,11 +7011,11 @@ function inspectBufferedEventGraph(value, remainingBytes) { const description = Reflect.apply(symbolDescriptionGetter, current, []); return charge(8 + (description?.length ?? 0) * 2); })) { - bytes = remainingBytes + 1; + bytes2 = remainingBytes + 1; } }; - const visit = (current, depth, isBlobInternalHandle = false) => { - if (bytes > remainingBytes) { + const visit3 = (current, depth, isBlobInternalHandle = false) => { + if (bytes2 > remainingBytes) { return; } if (typeof current === "string") { @@ -7027,7 +7027,7 @@ function inspectBufferedEventGraph(value, remainingBytes) { return; } if (typeof current === "function") { - bytes = remainingBytes + 1; + bytes2 = remainingBytes + 1; return; } if (current === null || typeof current !== "object") { @@ -7035,11 +7035,11 @@ function inspectBufferedEventGraph(value, remainingBytes) { return; } if (nativeProxyDetector?.(current)) { - bytes = remainingBytes + 1; + bytes2 = remainingBytes + 1; return; } if (depth >= MAX_BUFFERED_EVENT_DEPTH) { - bytes = remainingBytes + 1; + bytes2 = remainingBytes + 1; return; } if (visited.has(current)) { @@ -7052,8 +7052,8 @@ function inspectBufferedEventGraph(value, remainingBytes) { if (!charge(16)) { return false; } - const retainedStorage = estimateRetainedBufferBytes(current, visit, depth); - if (!visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit, retainIdentity)) { + const retainedStorage = estimateRetainedBufferBytes(current, visit3, depth); + if (!visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit3, retainIdentity)) { return false; } if (retainedStorage !== void 0 && !charge(retainedStorage.bytes)) { @@ -7063,22 +7063,22 @@ function inspectBufferedEventGraph(value, remainingBytes) { if (!charge(overhead)) { return false; } - visit(hiddenValue, depth + 1); - return bytes <= remainingBytes; + visit3(hiddenValue, depth + 1); + return bytes2 <= remainingBytes; })) { return false; } - return visitInspectableEventProperties(current, retainedStorage?.kind, depth, availableBytes, charge, visit); + return visitInspectableEventProperties(current, retainedStorage?.kind, depth, availableBytes, charge, visit3); })) { - bytes = remainingBytes + 1; + bytes2 = remainingBytes + 1; } }; try { - visit(value, 0); + visit3(value, 0); } catch { return void 0; } - return bytes <= remainingBytes ? { scalarBytes, roots, nodes } : void 0; + return bytes2 <= remainingBytes ? { scalarBytes, roots, nodes } : void 0; } function areBufferedRetainedEdgesEqual(first, second) { if (first.size !== second.size) { @@ -7261,7 +7261,7 @@ function applyBufferedLedgerChanges(records, changes, memberships) { } function createBufferedEventLedger() { const records = /* @__PURE__ */ new Map(); - let bytes = 0; + let bytes2 = 0; const reconcile = (entry, graph, isNew) => { const work = { remaining: MAX_BUFFERED_LEDGER_RECONCILIATION_WORK }; const changes = /* @__PURE__ */ new Map(); @@ -7273,26 +7273,26 @@ function createBufferedEventLedger() { if (!memberships) { return false; } - const projectedBytes = projectBufferedLedgerBytes(bytes, entry, graph, isNew, changes, records); + const projectedBytes = projectBufferedLedgerBytes(bytes2, entry, graph, isNew, changes, records); if (projectedBytes === void 0) { return false; } applyBufferedLedgerChanges(records, changes, memberships); entry.scalarBytes = graph.scalarBytes; entry.roots = graph.roots; - bytes = projectedBytes; + bytes2 = projectedBytes; return true; }; const release = (entry) => { - bytes -= getBufferedLedgerEntryBytes(entry); + bytes2 -= getBufferedLedgerEntryBytes(entry); for (const identity of entry.identities) { const record = records.get(identity); if (!record?.owners.delete(entry)) { continue; } - bytes -= BUFFERED_LEDGER_OWNER_BYTES; + bytes2 -= BUFFERED_LEDGER_OWNER_BYTES; if (record.owners.size === 0) { - bytes -= getBufferedLedgerNodeBytes(record, 0); + bytes2 -= getBufferedLedgerNodeBytes(record, 0); records.delete(identity); } } @@ -7309,7 +7309,7 @@ function createBufferedEventLedger() { release, clear() { records.clear(); - bytes = 0; + bytes2 = 0; } }; } @@ -7683,7 +7683,7 @@ var init_EventStream = __esm({ const readQueue = createEventQueue(); const bufferedLedger = createBufferedEventLedger(); let ended = this.ended; - let failure; + let failure2; let failureDelivered = false; let detach = () => void 0; const doneResult = () => ({ value: void 0, done: true }); @@ -7693,11 +7693,11 @@ var init_EventStream = __esm({ } }; const rejectReader = () => { - if (!failure || failureDelivered || !readQueue.length) { + if (!failure2 || failureDelivered || !readQueue.length) { return; } failureDelivered = true; - readQueue.dequeue().reject(failure); + readQueue.dequeue().reject(failure2); }; const cleanup = () => { detach(); @@ -7780,13 +7780,13 @@ var init_EventStream = __esm({ } }; const onFailure = (error) => { - failure = error; + failure2 = error; if (!pushQueue.length) { rejectReader(); } }; const adoptTerminalFailure = () => { - if (failure) { + if (failure2) { return; } const terminal = __classPrivateFieldGet(this, _EventStream_terminalFailure, "f"); @@ -7794,7 +7794,7 @@ var init_EventStream = __esm({ return; } if (terminal.kind === "error" ? rejectOnError : rejectOnAbort) { - failure = terminal.error; + failure2 = terminal.error; } }; const onEnd = () => { @@ -7834,9 +7834,9 @@ var init_EventStream = __esm({ if (ended || this.ended) { adoptTerminalFailure(); } - if (failure && !failureDelivered) { + if (failure2 && !failureDelivered) { failureDelivered = true; - return Promise.reject(failure); + return Promise.reject(failure2); } if (ended) { return Promise.resolve(doneResult()); @@ -8614,22 +8614,22 @@ var init_parser2 = __esm({ const parseObj = () => { index++; skipBlank(); - const obj = {}; + const obj2 = {}; try { while (jsonString[index] !== "}") { skipBlank(); if (index >= length && Allow.OBJ & allow) { - return obj; + return obj2; } const key = parseStr(); skipBlank(); index++; try { const value = parseAny(); - Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + Object.defineProperty(obj2, key, { value, writable: true, enumerable: true, configurable: true }); } catch (e) { if (Allow.OBJ & allow) { - return obj; + return obj2; } throw e; } @@ -8640,19 +8640,19 @@ var init_parser2 = __esm({ } } catch { if (Allow.OBJ & allow) { - return obj; + return obj2; } markPartialJSON("Expected '}' at end of object"); } index++; - return obj; + return obj2; }; const parseArr = () => { index++; - const arr = []; + const arr2 = []; try { while (jsonString[index] !== "]") { - arr.push(parseAny()); + arr2.push(parseAny()); skipBlank(); if (jsonString[index] === ",") { index++; @@ -8660,12 +8660,12 @@ var init_parser2 = __esm({ } } catch { if (Allow.ARR & allow) { - return arr; + return arr2; } markPartialJSON("Expected ']' at end of array"); } index++; - return arr; + return arr2; }; const parseNum = () => { if (index === 0) { @@ -8781,29 +8781,29 @@ function recordPartialJSONFragment(state2, budget, fragment, validationWorkBudge if (budget.fragments >= MAX_PARTIAL_JSON_FRAGMENTS) { throw new OpenAIError("Chat completion stream exceeded its structured JSON fragment limit"); } - let bytes = 0; + let bytes2 = 0; let { depth, escaped, has_non_whitespace: hasNonWhitespace, in_string: inString } = state2; let completed = false; let firstCharacter = true; for (const character of fragment) { - const previousBytes = bytes; + const previousBytes = bytes2; const codePoint = character.codePointAt(0); if (firstCharacter && state2.pending_high_surrogate && codePoint >= 56320 && codePoint <= 57343) { - bytes += 1; + bytes2 += 1; } else if (codePoint <= 127) { - bytes += 1; + bytes2 += 1; } else if (codePoint <= 2047) { - bytes += 2; + bytes2 += 2; } else if (codePoint <= 65535) { - bytes += 3; + bytes2 += 3; } else { - bytes += 4; + bytes2 += 4; } firstCharacter = false; - if (budget.bytes + bytes > MAX_PARTIAL_JSON_BYTES) { + if (budget.bytes + bytes2 > MAX_PARTIAL_JSON_BYTES) { throw new OpenAIError("Chat completion stream exceeded its structured JSON byte limit"); } - if (validationWorkBudget && validationWorkBudget.work + bytes > MAX_PARTIAL_JSON_PARSE_WORK) { + if (validationWorkBudget && validationWorkBudget.work + bytes2 > MAX_PARTIAL_JSON_PARSE_WORK) { validationWorkBudget.work += previousBytes; throw new OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit"); } @@ -8833,7 +8833,7 @@ function recordPartialJSONFragment(state2, budget, fragment, validationWorkBudge completed || (completed = depth === 0); } } - state2.bytes += bytes; + state2.bytes += bytes2; state2.fragments += 1; state2.depth = depth; state2.escaped = escaped; @@ -8843,12 +8843,12 @@ function recordPartialJSONFragment(state2, budget, fragment, validationWorkBudge const finalCodeUnit = fragment.codePointAt(fragment.length - 1) ?? 0; state2.pending_high_surrogate = finalCodeUnit >= 55296 && finalCodeUnit <= 56319; } - budget.bytes += bytes; + budget.bytes += bytes2; budget.fragments += 1; if (validationWorkBudget) { - validationWorkBudget.work += bytes; + validationWorkBudget.work += bytes2; } - if (!hasNonWhitespace || bytes === 0) { + if (!hasNonWhitespace || bytes2 === 0) { return false; } const minimumGrowth = Math.max(EAGER_PARTIAL_JSON_BYTES, Math.floor(state2.last_parsed_bytes / 2)); @@ -8921,7 +8921,7 @@ function captureSnapshotArrayItem(array, index) { } return descriptor.value; } -function mapCapturedSnapshotArray(array, maximum, kind, map) { +function mapCapturedSnapshotArray(array, maximum, kind, map3) { const descriptor = Object.getOwnPropertyDescriptor(array, "length"); const length = descriptor && "value" in descriptor ? descriptor.value : void 0; if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > maximum) { @@ -8937,7 +8937,7 @@ function mapCapturedSnapshotArray(array, maximum, kind, map) { if (!("value" in item)) { throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot"); } - mapped[index] = map(item.value, index); + mapped[index] = map3(item.value, index); } return mapped; } @@ -9043,14 +9043,14 @@ function snapshotChatCompletionParserParams(params) { } function canonicalSerializedParserSchema(value, budget) { const ancestors = /* @__PURE__ */ new WeakSet(); - const charge = (bytes) => { - if (!Number.isSafeInteger(bytes) || bytes < 0 || budget.bytes + bytes > MAX_SERIALIZED_PARSER_SCHEMA_BYTES) { + const charge = (bytes2) => { + if (!Number.isSafeInteger(bytes2) || bytes2 < 0 || budget.bytes + bytes2 > MAX_SERIALIZED_PARSER_SCHEMA_BYTES) { return false; } - budget.bytes += bytes; + budget.bytes += bytes2; return true; }; - const visit = (current, depth) => { + const visit3 = (current, depth) => { if (depth > MAX_SERIALIZED_PARSER_SCHEMA_DEPTH || budget.nodes >= MAX_SERIALIZED_PARSER_SCHEMA_NODES) { return UNSAFE_SERIALIZED_PARSER_VALUE; } @@ -9118,7 +9118,7 @@ function canonicalSerializedParserSchema(value, budget) { if (!("value" in descriptor)) { return UNSAFE_SERIALIZED_PARSER_VALUE; } - const item = visit(descriptor.value, depth + 1); + const item = visit3(descriptor.value, depth + 1); if (item === UNSAFE_SERIALIZED_PARSER_VALUE) { return item; } @@ -9155,7 +9155,7 @@ function canonicalSerializedParserSchema(value, budget) { }); const fields = []; for (const [key, entry] of entries) { - const normalized = visit(entry, depth + 1); + const normalized = visit3(entry, depth + 1); if (normalized === UNSAFE_SERIALIZED_PARSER_VALUE) { return normalized; } @@ -9173,7 +9173,7 @@ function canonicalSerializedParserSchema(value, budget) { } }; try { - const normalized = visit(value, 0); + const normalized = visit3(value, 0); return typeof normalized === "string" ? normalized : void 0; } catch { return void 0; @@ -9181,11 +9181,11 @@ function canonicalSerializedParserSchema(value, budget) { } function rememberSerializedParserSchema(signatures, source, holder, key) { const parser = Object.getOwnPropertyDescriptor(source, "$parseRaw"); - const schema = Object.getOwnPropertyDescriptor(holder, key); - if (!parser || !("value" in parser) || typeof parser.value !== "function" || !schema || !("value" in schema)) { + const schema4 = Object.getOwnPropertyDescriptor(holder, key); + if (!parser || !("value" in parser) || typeof parser.value !== "function" || !schema4 || !("value" in schema4)) { return; } - const normalized = canonicalSerializedParserSchema(schema.value, { nodes: 0, bytes: 0 }); + const normalized = canonicalSerializedParserSchema(schema4.value, { nodes: 0, bytes: 0 }); if (normalized !== void 0) { signatures.set(source, normalized); } @@ -9563,8 +9563,8 @@ function finalizeChatCompletion(snapshot, params, audioDoneChoiceIndexes, valida function isCompleteAudio(audio) { return audio?.id != null && audio.data != null && audio.transcript != null && audio.expires_at != null; } -function assertIsEmpty(obj) { - void obj; +function assertIsEmpty(obj2) { + void obj2; } function assertNever(_x) { return _x; @@ -15443,13 +15443,13 @@ var init_base64 = __esm({ "node_modules/openai/internal/utils/base64.mjs"() { init_error(); init_bytes(); - fromBase64 = (str) => { + fromBase64 = (str2) => { if (typeof globalThis.Buffer !== "undefined") { - const buf = globalThis.Buffer.from(str, "base64"); + const buf = globalThis.Buffer.from(str2, "base64"); return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); } if (typeof atob !== "undefined") { - const bstr = atob(str); + const bstr = atob(str2); const buf = new Uint8Array(bstr.length); for (let i = 0; i < bstr.length; i++) { buf[i] = bstr.charCodeAt(i); @@ -15468,11 +15468,11 @@ var init_base64 = __esm({ } else { const binaryStr = atob(base64Str); const len = binaryStr.length; - const bytes = new Uint8Array(len); + const bytes2 = new Uint8Array(len); for (let i = 0; i < len; i++) { - bytes[i] = binaryStr.charCodeAt(i); + bytes2[i] = binaryStr.charCodeAt(i); } - return Array.from(new Float32Array(bytes.buffer)); + return Array.from(new Float32Array(bytes2.buffer)); } }; } @@ -17390,17 +17390,17 @@ var init_evals = __esm({ async function waitForFileProcessing(resource, id, pollInterval, maxWait) { const terminalStates = /* @__PURE__ */ new Set(["processed", "error", "deleted"]); const start = performance.now(); - let file = await resource.retrieve(id); - while (!file.status || !terminalStates.has(file.status)) { + let file2 = await resource.retrieve(id); + while (!file2.status || !terminalStates.has(file2.status)) { await sleep(pollInterval); - file = await resource.retrieve(id); + file2 = await resource.retrieve(id); if (performance.now() - start > maxWait) { throw new APIConnectionTimeoutError({ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.` }); } } - return file; + return file2; } var init_file_processing = __esm({ "node_modules/openai/lib/file-processing.mjs"() { @@ -20517,8 +20517,8 @@ var init_files4 = __esm({ * Attach a file to the given vector store and wait for it to be processed. */ async createAndPoll(vectorStoreId, body, options) { - const file = await this.create(vectorStoreId, body, options); - return await this.poll(vectorStoreId, file.id, options); + const file2 = await this.create(vectorStoreId, body, options); + return await this.poll(vectorStoreId, file2.id, options); } /** * Wait for the vector store file to finish processing. @@ -20535,15 +20535,15 @@ var init_files4 = __esm({ * Note the file will be asynchronously processed (you can use the alternative * polling helper method to wait for processing to complete). */ - async upload(vectorStoreId, file, options) { - const fileInfo = await this._client.files.create({ file, purpose: "assistants" }, options); + async upload(vectorStoreId, file2, options) { + const fileInfo = await this._client.files.create({ file: file2, purpose: "assistants" }, options); return this.create(vectorStoreId, { file_id: fileInfo.id }, options); } /** * Add a file to a vector store and poll until processing is complete. */ - async uploadAndPoll(vectorStoreId, file, options) { - const fileInfo = await this.upload(vectorStoreId, file, options); + async uploadAndPoll(vectorStoreId, file2, options) { + const fileInfo = await this.upload(vectorStoreId, file2, options); return await this.poll(vectorStoreId, fileInfo.id, options); } /** @@ -20811,8 +20811,8 @@ function selectMatchingSignature(signatureHeader, expectedSignature, firstSignat } return matchingSignature; } -async function verifyWebhookSignature(payload, signatureHeader, timestamp, webhookId, secret, tolerance) { - const timestampSeconds = Number.parseInt(timestamp, 10); +async function verifyWebhookSignature(payload, signatureHeader, timestamp2, webhookId, secret, tolerance) { + const timestampSeconds = Number.parseInt(timestamp2, 10); if (Number.isNaN(timestampSeconds)) { throw new InvalidWebhookSignatureError("Invalid webhook timestamp format"); } @@ -20829,7 +20829,7 @@ async function verifyWebhookSignature(payload, signatureHeader, timestamp, webho throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature"); } const decodedSecret = Uint8Array.from(secret.startsWith("whsec_") ? fromBase64(secret.slice("whsec_".length)) : encodeUTF8(secret)); - const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; + const signedPayload = webhookId ? `${webhookId}.${timestamp2}.${payload}` : `${timestamp2}.${payload}`; const signedPayloadBytes = Uint8Array.from(encodeUTF8(signedPayload)); const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, useBoundedVerification ? ["sign", "verify"] : ["verify"]); if (useBoundedVerification && firstSignature) { @@ -21045,12 +21045,12 @@ var init_webhooks = __esm({ __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); const headersObj = buildHeaders([headers]).values; const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature"); - const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp"); + const timestamp2 = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp"); const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id"); if (webhookSignatureRequiresSigning(signatureHeader) && typeof crypto.subtle.sign !== "function") { throw new Error("Webhook signature verification is only supported when the `crypto` global is defined"); } - return await verifyWebhookSignature(payload, signatureHeader, timestamp, webhookId, secret, tolerance); + return await verifyWebhookSignature(payload, signatureHeader, timestamp2, webhookId, secret, tolerance); } }; _Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret2(secret) { @@ -21627,17 +21627,17 @@ var init_client = __esm({ const request2 = authentication instanceof X509WorkloadIdentityAuth ? Promise.resolve(options).then((resolved) => authentication.runRequest(() => this.makeRequest(resolved, remainingRetries, void 0), this)) : this.makeRequest(options, remainingRetries, void 0); return this.responsePromise(request2); } - responsePromise(request2, parse = (client, props) => this.parseResponseWithTimeout(client, props)) { + responsePromise(request2, parse2 = (client, props) => this.parseResponseWithTimeout(client, props)) { const promise = new APIPromise(this, request2, (client, props) => { const resume = __classPrivateFieldGet(this, _OpenAI_responseAttempts, "f").get(props.controller)?.continueRequest; - return resume ? resume(() => parse(client, props)) : parse(client, props); + return resume ? resume(() => parse2(client, props)) : parse2(client, props); }); promise.withResponse = async () => { const data = await promise; const { response } = await request2; return { data, response, request_id: response.headers.get("x-request-id") }; }; - promise._thenUnwrap = (transform) => this.responsePromise(request2, async (client, props) => addRequestID(transform(await parse(client, props), props), props.response)); + promise._thenUnwrap = (transform) => this.responsePromise(request2, async (client, props) => addRequestID(transform(await parse2(client, props), props), props.response)); return promise; } async parseResponseWithTimeout(client, props) { @@ -22400,72 +22400,72 @@ var init_provider_env = __esm({ function isJsonSchemaObject(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } -function isStructuredSchema(schema) { - if (!isJsonSchemaObject(schema)) +function isStructuredSchema(schema4) { + if (!isJsonSchemaObject(schema4)) return false; - const types = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : []; - return types.includes("object") || types.includes("array") || schema.properties !== void 0 || schema.items !== void 0; + const types = typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : []; + return types.includes("object") || types.includes("array") || schema4.properties !== void 0 || schema4.items !== void 0; } -function schemaAllowsNull(schema) { - if (!isJsonSchemaObject(schema)) +function schemaAllowsNull(schema4) { + if (!isJsonSchemaObject(schema4)) return false; - if (schema.type === "null" || Array.isArray(schema.type) && schema.type.includes("null")) + if (schema4.type === "null" || Array.isArray(schema4.type) && schema4.type.includes("null")) return true; - if (schema.const === null || Array.isArray(schema.enum) && schema.enum.includes(null)) + if (schema4.const === null || Array.isArray(schema4.enum) && schema4.enum.includes(null)) return true; - return Array.isArray(schema.anyOf) && schema.anyOf.some((variant) => schemaAllowsNull(variant)); + return Array.isArray(schema4.anyOf) && schema4.anyOf.some((variant) => schemaAllowsNull(variant)); } -function makeJsonSchemaNodeStrict(schema, isUnsupportedKeyword) { - if (!isJsonSchemaObject(schema)) { +function makeJsonSchemaNodeStrict(schema4, isUnsupportedKeyword) { + if (!isJsonSchemaObject(schema4)) { throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported"); } for (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) { - if (schema[key] !== void 0) { + if (schema4[key] !== void 0) { throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`); } } if (isUnsupportedKeyword) { - for (const [key, value] of Object.entries(schema)) { + for (const [key, value] of Object.entries(schema4)) { if (isUnsupportedKeyword(key, value)) { throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`); } } } - if (schema.anyOf !== void 0) { - if (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) { + if (schema4.anyOf !== void 0) { + if (!Array.isArray(schema4.anyOf) || schema4.anyOf.length === 0) { throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema"); } - for (const variant of schema.anyOf) { + for (const variant of schema4.anyOf) { if (isStructuredSchema(variant)) { throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported"); } makeJsonSchemaNodeStrict(variant, isUnsupportedKeyword); } } - if (schema.items !== void 0) { - if (Array.isArray(schema.items)) { + if (schema4.items !== void 0) { + if (Array.isArray(schema4.items)) { throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported"); } - makeJsonSchemaNodeStrict(schema.items, isUnsupportedKeyword); + makeJsonSchemaNodeStrict(schema4.items, isUnsupportedKeyword); } - const isObjectSchema = schema.type === "object"; - if (schema.properties !== void 0 && !isObjectSchema) { + const isObjectSchema = schema4.type === "object"; + if (schema4.properties !== void 0 && !isObjectSchema) { throw new UnsupportedStrictJsonSchemaError("properties require type object"); } if (!isObjectSchema) return; - if (schema.additionalProperties !== void 0 && schema.additionalProperties !== false) { + if (schema4.additionalProperties !== void 0 && schema4.additionalProperties !== false) { throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported"); } - if (schema.properties !== void 0 && !isJsonSchemaObject(schema.properties)) { + if (schema4.properties !== void 0 && !isJsonSchemaObject(schema4.properties)) { throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map"); } - if (schema.required !== void 0 && (!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== "string"))) { + if (schema4.required !== void 0 && (!Array.isArray(schema4.required) || schema4.required.some((key) => typeof key !== "string"))) { throw new UnsupportedStrictJsonSchemaError("object required must be a string array"); } - const properties = schema.properties ?? {}; + const properties = schema4.properties ?? {}; const propertyNames = Object.keys(properties); - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); if ([...required].some((key) => !propertyNames.includes(key))) { throw new UnsupportedStrictJsonSchemaError("required contains an unknown property"); } @@ -22475,11 +22475,11 @@ function makeJsonSchemaNodeStrict(schema, isUnsupportedKeyword) { properties[key] = { anyOf: [property, { type: "null" }] }; } } - schema.required = propertyNames; - schema.additionalProperties = false; + schema4.required = propertyNames; + schema4.additionalProperties = false; } -function makeStrictJsonSchema(schema, isUnsupportedKeyword) { - const cloned = structuredClone(schema); +function makeStrictJsonSchema(schema4, isUnsupportedKeyword) { + const cloned = structuredClone(schema4); if (!isJsonSchemaObject(cloned)) { throw new UnsupportedStrictJsonSchemaError("root schema must have type object"); } @@ -22537,18 +22537,18 @@ function grammarToolInputJsonStart(buffer, inputProperty) { return `{${JSON.stringify(inputProperty)}:"`; } function inferGrammarInputProperty(tool) { - const schema = tool.parameters; - if (schema.type !== "object") { + const schema4 = tool.parameters; + if (schema4.type !== "object") { throw new Error("grammar constrained sampling requires an object parameter schema"); } - if (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== "string") { + if (!Array.isArray(schema4.required) || schema4.required.length !== 1 || typeof schema4.required[0] !== "string") { throw new Error("grammar constrained sampling requires exactly one required string property"); } - const inputProperty = schema.required[0]; - if (!schema.properties?.[inputProperty]) { + const inputProperty = schema4.required[0]; + if (!schema4.properties?.[inputProperty]) { throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`); } - if (schema.properties[inputProperty]?.type !== "string") { + if (schema4.properties[inputProperty]?.type !== "string") { throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`); } return inputProperty; @@ -22689,11 +22689,11 @@ var init_openai_prompt_cache = __esm({ }); // node_modules/@earendil-works/pi-ai/dist/utils/hash.js -function shortHash(str) { +function shortHash(str2) { let h1 = 3735928559; let h2 = 1103547991; - for (let i = 0; i < str.length; i++) { - const ch = str.charCodeAt(i); + for (let i = 0; i < str2.length; i++) { + const ch = str2.charCodeAt(i); h1 = Math.imul(h1 ^ ch, 2654435761); h2 = Math.imul(h2 ^ ch, 1597334677); } @@ -22854,21 +22854,21 @@ var require_dist = __commonJS({ const parseObj = () => { index++; skipBlank(); - const obj = {}; + const obj2 = {}; try { while (jsonString[index] !== "}") { skipBlank(); if (index >= length && options_1.Allow.OBJ & allow) - return obj; + return obj2; const key = parseStr(); skipBlank(); index++; try { const value = parseAny(); - obj[key] = value; + obj2[key] = value; } catch (e) { if (options_1.Allow.OBJ & allow) - return obj; + return obj2; else throw e; } @@ -22878,19 +22878,19 @@ var require_dist = __commonJS({ } } catch (e) { if (options_1.Allow.OBJ & allow) - return obj; + return obj2; else markPartialJSON("Expected '}' at end of object"); } index++; - return obj; + return obj2; }; const parseArr = () => { index++; - const arr = []; + const arr2 = []; try { while (jsonString[index] !== "]") { - arr.push(parseAny()); + arr2.push(parseAny()); skipBlank(); if (jsonString[index] === ",") { index++; @@ -22898,12 +22898,12 @@ var require_dist = __commonJS({ } } catch (e) { if (options_1.Allow.ARR & allow) { - return arr; + return arr2; } markPartialJSON("Expected ']' at end of array"); } index++; - return arr; + return arr2; }; const parseNum = () => { if (index === 0) { @@ -22946,8 +22946,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON2; - exports.parse = parse; + var parse2 = parseJSON2; + exports.parse = parse2; } }); @@ -25011,18 +25011,18 @@ function maybeObj2(x) { } return x ?? {}; } -function isEmptyObj2(obj) { - if (!obj) +function isEmptyObj2(obj2) { + if (!obj2) return true; - for (const _k in obj) + for (const _k in obj2) return false; return true; } -function hasOwn2(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); +function hasOwn2(obj2, key) { + return Object.prototype.hasOwnProperty.call(obj2, key); } -function isObj2(obj) { - return obj != null && typeof obj === "object" && !Array.isArray(obj); +function isObj2(obj2) { + return obj2 != null && typeof obj2 === "object" && !Array.isArray(obj2); } function checkNever(_value) { } @@ -25355,11 +25355,11 @@ var init_formats2 = __esm({ }); // node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs -function is_buffer2(obj) { - if (!obj || typeof obj !== "object") { +function is_buffer2(obj2) { + if (!obj2 || typeof obj2 !== "object") { return false; } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + return !!(obj2.constructor && obj2.constructor.isBuffer && obj2.constructor.isBuffer(obj2)); } function maybe_map2(val, fn) { if (isArray2(val)) { @@ -25376,7 +25376,7 @@ var init_utils3 = __esm({ "node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"() { init_formats2(); init_values2(); - has2 = (obj, key) => (has2 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has2(obj, key)); + has2 = (obj2, key) => (has2 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has2(obj2, key)); hex_table2 = /* @__PURE__ */ (() => { const array = []; for (let i = 0; i < 256; ++i) { @@ -25385,25 +25385,25 @@ var init_utils3 = __esm({ return array; })(); limit2 = 1024; - encode2 = (str, _defaultEncoder, charset, _kind, format) => { - if (str.length === 0) { - return str; + encode2 = (str2, _defaultEncoder, charset, _kind, format) => { + if (str2.length === 0) { + return str2; } - let string = str; - if (typeof str === "symbol") { - string = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string = String(str); + let string2 = str2; + if (typeof str2 === "symbol") { + string2 = Symbol.prototype.toString.call(str2); + } else if (typeof str2 !== "string") { + string2 = String(str2); } if (charset === "iso-8859-1") { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) { return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; }); } let out = ""; - for (let j = 0; j < string.length; j += limit2) { - const segment = string.length >= limit2 ? string.slice(j, j + limit2) : string; - const arr = []; + for (let j = 0; j < string2.length; j += limit2) { + const segment = string2.length >= limit2 ? string2.slice(j, j + limit2) : string2; + const arr2 = []; for (let i = 0; i < segment.length; ++i) { let c = segment.charCodeAt(i); if (c === 45 || // - @@ -25414,26 +25414,26 @@ var init_utils3 = __esm({ c >= 65 && c <= 90 || // a-z c >= 97 && c <= 122 || // A-Z format === RFC17382 && (c === 40 || c === 41)) { - arr[arr.length] = segment.charAt(i); + arr2[arr2.length] = segment.charAt(i); continue; } if (c < 128) { - arr[arr.length] = hex_table2[c]; + arr2[arr2.length] = hex_table2[c]; continue; } if (c < 2048) { - arr[arr.length] = hex_table2[192 | c >> 6] + hex_table2[128 | c & 63]; + arr2[arr2.length] = hex_table2[192 | c >> 6] + hex_table2[128 | c & 63]; continue; } if (c < 55296 || c >= 57344) { - arr[arr.length] = hex_table2[224 | c >> 12] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; + arr2[arr2.length] = hex_table2[224 | c >> 12] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; continue; } i += 1; c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); - arr[arr.length] = hex_table2[240 | c >> 18] + hex_table2[128 | c >> 12 & 63] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; + arr2[arr2.length] = hex_table2[240 | c >> 18] + hex_table2[128 | c >> 12 & 63] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63]; } - out += arr.join(""); + out += arr2.join(""); } return out; }; @@ -25444,8 +25444,8 @@ var init_utils3 = __esm({ function is_non_nullish_primitive2(v) { return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; } -function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; +function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder3, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj2 = object; let tmp_sc = sideChannel; let step = 0; let find_flag = false; @@ -25464,68 +25464,68 @@ function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, a } } if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } else if (generateArrayPrefix === "comma" && isArray2(obj)) { - obj = maybe_map2(obj, function(value) { + obj2 = filter(prefix, obj2); + } else if (obj2 instanceof Date) { + obj2 = serializeDate?.(obj2); + } else if (generateArrayPrefix === "comma" && isArray2(obj2)) { + obj2 = maybe_map2(obj2, function(value) { if (value instanceof Date) { return serializeDate?.(value); } return value; }); } - if (obj === null) { + if (obj2 === null) { if (strictNullHandling) { - return encoder && !encodeValuesOnly ? ( + return encoder3 && !encodeValuesOnly ? ( // @ts-expect-error - encoder(prefix, defaults2.encoder, charset, "key", format) + encoder3(prefix, defaults2.encoder, charset, "key", format) ) : prefix; } - obj = ""; + obj2 = ""; } - if (is_non_nullish_primitive2(obj) || is_buffer2(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format); + if (is_non_nullish_primitive2(obj2) || is_buffer2(obj2)) { + if (encoder3) { + const key_value = encodeValuesOnly ? prefix : encoder3(prefix, defaults2.encoder, charset, "key", format); return [ formatter?.(key_value) + "=" + // @ts-expect-error - formatter?.(encoder(obj, defaults2.encoder, charset, "value", format)) + formatter?.(encoder3(obj2, defaults2.encoder, charset, "value", format)) ]; } - return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + return [formatter?.(prefix) + "=" + formatter?.(String(obj2))]; } const values = []; - if (typeof obj === "undefined") { + if (typeof obj2 === "undefined") { return values; } let obj_keys; - if (generateArrayPrefix === "comma" && isArray2(obj)) { - if (encodeValuesOnly && encoder) { - obj = maybe_map2(obj, encoder); + if (generateArrayPrefix === "comma" && isArray2(obj2)) { + if (encodeValuesOnly && encoder3) { + obj2 = maybe_map2(obj2, encoder3); } - obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + obj_keys = [{ value: obj2.length > 0 ? obj2.join(",") || null : void 0 }]; } else if (isArray2(filter)) { obj_keys = filter; } else { - const keys = Object.keys(obj); + const keys = Object.keys(obj2); obj_keys = sort ? keys.sort(sort) : keys; } const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - const adjusted_prefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; - if (allowEmptyArrays && isArray2(obj) && obj.length === 0) { + const adjusted_prefix = commaRoundTrip && isArray2(obj2) && obj2.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray2(obj2) && obj2.length === 0) { return adjusted_prefix + "[]"; } for (let j = 0; j < obj_keys.length; ++j) { const key = obj_keys[j]; const value = ( // @ts-ignore - typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj2[key] ); if (skipNulls && value === null) { continue; } const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; - const key_prefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + const key_prefix = isArray2(obj2) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); sideChannel.set(object, step); const valueSideChannel = /* @__PURE__ */ new WeakMap(); valueSideChannel.set(sentinel2, sideChannel); @@ -25539,7 +25539,7 @@ function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, a skipNulls, encodeDotInKeys, // @ts-ignore - generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder, + generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj2) ? null : encoder3, filter, sort, allowDots, @@ -25616,25 +25616,25 @@ function normalize_stringify_options2(opts = defaults2) { }; } function stringify2(object, opts = {}) { - let obj = object; + let obj2 = object; const options = normalize_stringify_options2(opts); let obj_keys; let filter; if (typeof options.filter === "function") { filter = options.filter; - obj = filter("", obj); + obj2 = filter("", obj2); } else if (isArray2(options.filter)) { filter = options.filter; obj_keys = filter; } const keys = []; - if (typeof obj !== "object" || obj === null) { + if (typeof obj2 !== "object" || obj2 === null) { return ""; } const generateArrayPrefix = array_prefix_generators2[options.arrayFormat]; const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; if (!obj_keys) { - obj_keys = Object.keys(obj); + obj_keys = Object.keys(obj2); } if (options.sort) { obj_keys.sort(options.sort); @@ -25642,11 +25642,11 @@ function stringify2(object, opts = {}) { const sideChannel = /* @__PURE__ */ new WeakMap(); for (let i = 0; i < obj_keys.length; ++i) { const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { + if (options.skipNulls && obj2[key] === null) { continue; } push_to_array3(keys, inner_stringify2( - obj[key], + obj2[key], key, // @ts-expect-error generateArrayPrefix, @@ -25696,8 +25696,8 @@ var init_stringify2 = __esm({ return String(prefix); } }; - push_to_array3 = function(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray2(value_or_array) ? value_or_array : [value_or_array]); + push_to_array3 = function(arr2, value_or_array) { + Array.prototype.push.apply(arr2, isArray2(value_or_array) ? value_or_array : [value_or_array]); }; defaults2 = { addQueryPrefix: false, @@ -25830,12 +25830,12 @@ function redactSensitive(body) { async function checkCredentialsFileSafety(path4, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) { if (typeof process === "undefined" || process.platform === "win32") return; - const { fs: fs2 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); + const { fs: fs3 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); let resolved = path4; let st; try { - resolved = await fs2.promises.realpath(path4); - st = await fs2.promises.stat(resolved); + resolved = await fs3.promises.realpath(path4); + st = await fs3.promises.stat(resolved); } catch { return; } @@ -25851,26 +25851,26 @@ async function checkCredentialsFileSafety(path4, onWarn = (m) => console.warn(`a } } async function writeCredentialsFileAtomic(targetPath, data) { - const { fs: fs2, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); + const { fs: fs3, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); const dir = path4.dirname(targetPath); - await fs2.promises.mkdir(dir, { recursive: true, mode: 448 }); + await fs3.promises.mkdir(dir, { recursive: true, mode: 448 }); const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; try { - const fh = await fs2.promises.open(tmpPath, "w", 384); + const fh = await fs3.promises.open(tmpPath, "w", 384); try { await fh.writeFile(JSON.stringify(data, null, 2)); await fh.sync(); } finally { await fh.close(); } - await fs2.promises.rename(tmpPath, targetPath); + await fs3.promises.rename(tmpPath, targetPath); } catch (err) { - await fs2.promises.unlink(tmpPath).catch(() => { + await fs3.promises.unlink(tmpPath).catch(() => { }); throw err; } try { - const dirFh = await fs2.promises.open(dir, "r"); + const dirFh = await fs3.promises.open(dir, "r"); try { await dirFh.sync(); } finally { @@ -26074,13 +26074,13 @@ function concatBytes(buffers) { } return output; } -function encodeUTF82(str) { - let encoder; - return (encodeUTF8_2 ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_2 = encoder.encode.bind(encoder)))(str); +function encodeUTF82(str2) { + let encoder3; + return (encodeUTF8_2 ?? (encoder3 = new globalThis.TextEncoder(), encodeUTF8_2 = encoder3.encode.bind(encoder3)))(str2); } -function decodeUTF82(bytes) { - let decoder; - return (decodeUTF8_2 ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_2 = decoder.decode.bind(decoder)))(bytes); +function decodeUTF82(bytes2) { + let decoder3; + return (decodeUTF8_2 ?? (decoder3 = new globalThis.TextDecoder(), decodeUTF8_2 = decoder3.decode.bind(decoder3)))(bytes2); } var encodeUTF8_2, decodeUTF8_2; var init_bytes2 = __esm({ @@ -26093,13 +26093,13 @@ var fromBase642; var init_base642 = __esm({ "node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"() { init_error3(); - fromBase642 = (str) => { + fromBase642 = (str2) => { if (typeof globalThis.Buffer !== "undefined") { - const buf = globalThis.Buffer.from(str, "base64"); + const buf = globalThis.Buffer.from(str2, "base64"); return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); } if (typeof atob !== "undefined") { - const bstr = atob(str); + const bstr = atob(str2); const buf = new Uint8Array(bstr.length); for (let i = 0; i < bstr.length; i++) { buf[i] = bstr.charCodeAt(i); @@ -26272,11 +26272,11 @@ var init_credentials2 = __esm({ return null; } validateProfileName(profileName); - const { fs: fs2, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); + const { fs: fs3, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); const configPath = path4.join(rootConfigPath, "configs", `${profileName}.json`); let configRaw; try { - configRaw = await fs2.promises.readFile(configPath, "utf-8"); + configRaw = await fs3.promises.readFile(configPath, "utf-8"); } catch (err) { if (err?.code !== "ENOENT") { throw new Error(`failed to read config file ${configPath}: ${err}`); @@ -26404,10 +26404,10 @@ var init_credentials2 = __esm({ if (profileName) { return profileName; } - const { fs: fs2, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); + const { fs: fs3, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); const filePath = path4.join(rootConfigPath, "active_config"); try { - return (await fs2.promises.readFile(filePath, "utf-8")).trim() || "default"; + return (await fs3.promises.readFile(filePath, "utf-8")).trim() || "default"; } catch (err) { if (err?.code !== "ENOENT") { throw new Error(`failed to read ${filePath}: ${err}`); @@ -26424,10 +26424,10 @@ function identityTokenFromFile(path4) { throw new AnthropicError("Identity token file path is empty"); } return async () => { - const { fs: fs2 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); + const { fs: fs3 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); let content; try { - content = await fs2.promises.readFile(path4, "utf-8"); + content = await fs3.promises.readFile(path4, "utf-8"); } catch (err) { throw new AnthropicError(`Failed to read identity token file at ${path4}: ${err}`); } @@ -26518,11 +26518,11 @@ var init_oidc_federation = __esm({ // node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs function userOAuthProvider(config) { return async (opts) => { - const { fs: fs2 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); + const { fs: fs3 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); await checkCredentialsFileSafety(config.credentialsPath, config.onSafetyWarning); let raw; try { - raw = await fs2.promises.readFile(config.credentialsPath, "utf-8"); + raw = await fs3.promises.readFile(config.credentialsPath, "utf-8"); } catch (err) { throw new WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`); } @@ -26626,12 +26626,12 @@ async function defaultCredentials(options, profile) { function buildProvider(config, credentialsPath, baseURL, options) { switch (config.authentication.type) { case "oidc_federation": { - const auth = config.authentication; - const identityProvider = resolveIdentityTokenProvider(auth); + const auth2 = config.authentication; + const identityProvider = resolveIdentityTokenProvider(auth2); if (!identityProvider) { throw new WorkloadIdentityError("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)"); } - if (!auth.federation_rule_id) { + if (!auth2.federation_rule_id) { throw new WorkloadIdentityError("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence)."); } if (!config.organization_id) { @@ -26639,9 +26639,9 @@ function buildProvider(config, credentialsPath, baseURL, options) { } const exchange = oidcFederationProvider({ identityTokenProvider: identityProvider, - federationRuleId: auth.federation_rule_id, + federationRuleId: auth2.federation_rule_id, organizationId: config.organization_id, - serviceAccountId: auth.service_account_id, + serviceAccountId: auth2.service_account_id, workspaceId: config.workspace_id, baseURL, fetch: options.fetch, @@ -26671,16 +26671,16 @@ function buildProvider(config, credentialsPath, baseURL, options) { } } } -function resolveIdentityTokenProvider(auth) { - if (auth.identity_token) { - const source = auth.identity_token.source; +function resolveIdentityTokenProvider(auth2) { + if (auth2.identity_token) { + const source = auth2.identity_token.source; if (source !== "file") { throw new WorkloadIdentityError(`identity_token.source "${source}" is not supported by this SDK version (only "file")`); } - if (!auth.identity_token.path) { + if (!auth2.identity_token.path) { throw new WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`); } - return identityTokenFromFile(auth.identity_token.path); + return identityTokenFromFile(auth2.identity_token.path); } const tokenFile = readEnv2("ANTHROPIC_IDENTITY_TOKEN_FILE"); if (tokenFile) { @@ -26694,11 +26694,11 @@ function resolveIdentityTokenProvider(auth) { } function cachedExchangeProvider(exchange, credentialsPath, onCacheWriteError, onSafetyWarning) { return async (opts) => { - const { fs: fs2 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); + const { fs: fs3 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports)); await checkCredentialsFileSafety(credentialsPath, onSafetyWarning); let existing; try { - const raw = await fs2.promises.readFile(credentialsPath, "utf-8"); + const raw = await fs3.promises.readFile(credentialsPath, "utf-8"); existing = JSON.parse(raw); const token = existing?.["access_token"]; if (token && !opts?.forceRefresh) { @@ -26834,12 +26834,12 @@ async function* _iterSSEMessages2(response, controller) { yield sse; } } -function partition2(str, delimiter) { - const index = str.indexOf(delimiter); +function partition2(str2, delimiter) { + const index = str2.indexOf(delimiter); if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + return [str2.substring(0, index), delimiter, str2.substring(index + delimiter.length)]; } - return [str, "", ""]; + return [str2, "", ""]; } var _Stream_client2, Stream2, SSEDecoder2; var init_streaming3 = __esm({ @@ -27014,8 +27014,8 @@ var init_streaming3 = __esm({ const { value, done } = await iter.next(); if (done) return ctrl.close(); - const bytes = encodeUTF82(JSON.stringify(value) + "\n"); - ctrl.enqueue(bytes); + const bytes2 = encodeUTF82(JSON.stringify(value) + "\n"); + ctrl.enqueue(bytes2); } catch (err) { ctrl.error(err); } @@ -27746,8 +27746,8 @@ var init_headers3 = __esm({ }); // node_modules/@anthropic-ai/sdk/internal/utils/path.mjs -function encodeURIPath2(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +function encodeURIPath2(str2) { + return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } var EMPTY2, createPathTagFunction2, path3; var init_path2 = __esm({ @@ -28304,9 +28304,9 @@ function stainlessHelperHeader(tools, messages) { return {}; return { [STAINLESS_HELPER_HEADER]: helpers.join(", ") }; } -function stainlessHelperHeaderFromFile(file) { - if (wasCreatedByStainlessHelper(file)) { - return { [STAINLESS_HELPER_HEADER]: file[SDK_HELPER_SYMBOL] }; +function stainlessHelperHeaderFromFile(file2) { + if (wasCreatedByStainlessHelper(file2)) { + return { [STAINLESS_HELPER_HEADER]: file2[SDK_HELPER_SYMBOL] }; } return {}; } @@ -29208,12 +29208,12 @@ var require_sha256 = __commonJS({ } exports2.hmac = hmac; function fillBuffer(buffer, hmac2, info, counter) { - var num = counter[0]; - if (num === 0) { + var num2 = counter[0]; + if (num2 === 0) { throw new Error("hkdf: cannot expand more"); } hmac2.reset(); - if (num > 1) { + if (num2 > 1) { hmac2.update(buffer); } if (info) { @@ -29389,17 +29389,17 @@ var require_dist2 = __commonJS({ if (!msgSignature || !msgId || !msgTimestamp) { throw new WebhookVerificationError("Missing required headers"); } - const timestamp = this.verifyTimestamp(msgTimestamp); - const computedSignature = this.sign(msgId, timestamp, payload); + const timestamp2 = this.verifyTimestamp(msgTimestamp); + const computedSignature = this.sign(msgId, timestamp2, payload); const expectedSignature = computedSignature.split(",")[1]; const passedSignatures = msgSignature.split(" "); - const encoder = new globalThis.TextEncoder(); + const encoder3 = new globalThis.TextEncoder(); for (const versionedSignature of passedSignatures) { const [version, signature] = versionedSignature.split(","); if (version !== "v1") { continue; } - if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) { + if ((0, timing_safe_equal_1.timingSafeEqual)(encoder3.encode(signature), encoder3.encode(expectedSignature))) { const payloadString = payload.toString(); if (payloadString === "") { return void 0; @@ -29413,32 +29413,32 @@ var require_dist2 = __commonJS({ } throw new WebhookVerificationError("No matching signature found"); } - sign(msgId, timestamp, payload) { + sign(msgId, timestamp2, payload) { if (typeof payload === "string") { } else if (payload.constructor.name === "Buffer") { payload = payload.toString(); } else { throw new Error("Expected payload to be of type string or Buffer."); } - const encoder = new TextEncoder(); - const timestampNumber = Math.floor(timestamp.getTime() / 1e3); - const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`); + const encoder3 = new TextEncoder(); + const timestampNumber = Math.floor(timestamp2.getTime() / 1e3); + const toSign = encoder3.encode(`${msgId}.${timestampNumber}.${payload}`); const expectedSignature = base64.encode(sha256.hmac(this.key, toSign)); return `v1,${expectedSignature}`; } verifyTimestamp(timestampHeader) { const now = Math.floor(Date.now() / 1e3); - const timestamp = parseInt(timestampHeader, 10); - if (Number.isNaN(timestamp)) { + const timestamp2 = parseInt(timestampHeader, 10); + if (Number.isNaN(timestamp2)) { throw new WebhookVerificationError("Invalid Signature Headers"); } - if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) { + if (now - timestamp2 > WEBHOOK_TOLERANCE_IN_SECONDS) { throw new WebhookVerificationError("Message timestamp too old"); } - if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) { + if (timestamp2 > now + WEBHOOK_TOLERANCE_IN_SECONDS) { throw new WebhookVerificationError("Message timestamp too new"); } - return new Date(timestamp * 1e3); + return new Date(timestamp2 * 1e3); } }; exports.Webhook = Webhook2; @@ -34037,7 +34037,7 @@ var init_BetaToolRunner = __esm({ } let definition = change.tool; if ("run" in change.tool) { - const { run, parse, close, ...rest } = change.tool; + const { run, parse: parse2, close, ...rest } = change.tool; definition = rest; } content.push({ type: "tool_addition", tool: { type: "tool_definition", definition } }); @@ -40114,7 +40114,7 @@ function consumeLine(text) { } async function* iterateSseMessages(body, signal) { const reader = body.getReader(); - const decoder = new TextDecoder(); + const decoder3 = new TextDecoder(); const state2 = { event: null, data: [], raw: [] }; let buffer = ""; try { @@ -40126,7 +40126,7 @@ async function* iterateSseMessages(body, signal) { if (done) { break; } - buffer += decoder.decode(value, { stream: true }); + buffer += decoder3.decode(value, { stream: true }); let consumed2 = consumeLine(buffer); while (consumed2) { buffer = consumed2.rest; @@ -40137,7 +40137,7 @@ async function* iterateSseMessages(body, signal) { consumed2 = consumeLine(buffer); } } - buffer += decoder.decode(); + buffer += decoder3.decode(); let consumed = consumeLine(buffer); while (consumed) { buffer = consumed.rest; @@ -40615,11 +40615,11 @@ function convertTools(tools, isOAuthToken2, supportsEagerToolInputStreaming, sup return tools.map((tool, index) => { const strict = disablePreferredStrictTools && prefersJsonSchemaStrictSampling(tool) ? void 0 : resolveJsonSchemaStrictSampling(tool, supportsStrictTools, isAnthropicStrictUnsupportedKeyword); const parameters = getJsonSchemaToolParameters(tool, strict); - const schema = parameters; + const schema4 = parameters; const legacyInputSchema = { type: "object", - properties: schema.properties ?? {}, - required: schema.required ?? [] + properties: schema4.properties ?? {}, + required: schema4.required ?? [] }; const inputSchema = strict === true ? { ...parameters, @@ -41316,16 +41316,18 @@ function anthropicProvider() { } // proxy-models.ts -async function proxyModels(proxy) { +async function proxyModels(proxy, readProxy2 = async () => proxy) { const models2 = createModels(); const base = proxy.base_url.replace(/\/$/, ""); let catalog = []; try { - const response = await fetch(`${base}/v1/models`, { - headers: { Authorization: `Bearer ${proxy.api_key}` }, - signal: AbortSignal.timeout(5e3) - }); - if (response.ok) catalog = (await response.json()).data ?? []; + if (proxy.base_url && proxy.api_key) { + const response = await fetch(`${base}/v1/models`, { + headers: { Authorization: `Bearer ${proxy.api_key}` }, + signal: AbortSignal.timeout(5e3) + }); + if (response.ok) catalog = (await response.json()).data ?? []; + } } catch { } for (const [provider2, api, path4, fallback2] of [ @@ -41367,17 +41369,3988 @@ async function proxyModels(proxy) { ...provider2, baseUrl: entries[0].baseUrl, getModels: () => entries, - auth: { apiKey: { name: "Sausage proxy", resolve: async () => ({ - auth: { apiKey: proxy.api_key, headers: { "Shopify-Usage-Tag": JSON.stringify(["pi", "sausage"]) } }, - source: "llm-proxy" - }) } } + auth: { apiKey: { name: "Sausage proxy", resolve: async () => { + const current = await readProxy2(); + if (!current.base_url || !current.api_key) throw new Error("Set proxy.base_url and proxy.api_key in /etc/sausage/config.yaml before a model request"); + return { auth: { + apiKey: current.api_key, + baseUrl: current.base_url.replace(/\/$/, "") + entries[0].baseUrl.slice(base.length), + headers: { "Shopify-Usage-Tag": JSON.stringify(["pi", "sausage"]) } + }, source: "/etc/sausage/config.yaml" }; + } } } }); } return models2; } +// node_modules/@earendil-works/pi-schema/dist/builders.js +function str(options = {}) { + return { type: "string", ...options }; +} +function num(options = {}) { + return { type: "number", ...options }; +} +function bool(options = {}) { + return { type: "boolean", ...options }; +} +function lit(value, options = {}) { + return { const: value, ...options }; +} +function union(schemas, options = {}) { + return { anyOf: schemas, ...options }; +} +function arr(items, options = {}) { + return { type: "array", items, ...options }; +} +var Optional = class { + schema; + constructor(schema4) { + this.schema = schema4; + } +}; +function opt(schema4) { + return new Optional(schema4); +} +function obj(properties, options = {}) { + const { open, ...annotations } = options; + const props = {}; + const required = []; + for (const [name, property] of Object.entries(properties)) { + if (property instanceof Optional) + props[name] = property.schema; + else { + props[name] = property; + required.push(name); + } + } + return { + type: "object", + properties: props, + ...required.length > 0 ? { required } : {}, + ...open === true ? {} : { additionalProperties: false }, + ...annotations + }; +} + +// node_modules/@earendil-works/pi-durable/dist/documents.js +function defineDoc(definition) { + validateDefinition(definition); + return { definition }; +} +function validateDefinition(definition) { + if (!Number.isSafeInteger(definition.version) || definition.version < 1) { + throw new TypeError(`Document ${definition.kind} version must be a positive integer`); + } +} + +// node_modules/@earendil-works/chord/dist/output.js +var encoder = new TextEncoder(); +var decoder = new TextDecoder("utf-8", { ignoreBOM: true }); +function characterEnd(bytes2, index) { + let end = index; + while (end > 0 && ((bytes2[end] ?? 0) & 192) === 128) + end--; + return end; +} +var runtimeBuffer = globalThis.Buffer; +var nonAsciiPattern = /[^\x00-\x7f]/; +function utf8ByteLength(content) { + if (runtimeBuffer) + return runtimeBuffer.byteLength(content, "utf8"); + const firstNonAscii = content.search(nonAsciiPattern); + if (firstNonAscii === -1) + return content.length; + let bytes2 = firstNonAscii; + for (let i = firstNonAscii; i < content.length; i++) { + const code = content.charCodeAt(i); + if (code <= 127) + bytes2 += 1; + else if (code <= 2047) + bytes2 += 2; + else if (code >= 55296 && code <= 56319 && i + 1 < content.length) { + const next = content.charCodeAt(i + 1); + if (next >= 56320 && next <= 57343) { + bytes2 += 4; + i++; + } else + bytes2 += 3; + } else + bytes2 += 3; + } + return bytes2; +} +var PROGRESS_BYTES_PER_SECOND = 100 * 1024; + +// node_modules/@earendil-works/pi-durable/dist/truncate.js +var DEFAULT_MAX_LINES = 2e3; +var DEFAULT_MAX_BYTES = 50 * 1024; +function splitLinesForCounting(content) { + if (content.length === 0) + return []; + const lines = content.split("\n"); + if (content.endsWith("\n")) + lines.pop(); + return lines; +} +function formatSize(bytes2) { + if (bytes2 < 1024) { + return `${bytes2}B`; + } else if (bytes2 < 1024 * 1024) { + return `${(bytes2 / 1024).toFixed(1)}KB`; + } else { + return `${(bytes2 / (1024 * 1024)).toFixed(1)}MB`; + } +} +function truncateHeadOf(prefix, totals, options = {}) { + const maxLines = options.maxLines ?? DEFAULT_MAX_LINES; + const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; + const totalBytes = totals.bytes; + const lines = splitLinesForCounting(prefix); + const totalLines = totals.lines; + if (totalLines <= maxLines && totalBytes <= maxBytes) { + return { + content: prefix, + truncated: false, + truncatedBy: null, + totalLines, + totalBytes, + outputLines: totalLines, + outputBytes: totalBytes, + lastLinePartial: false, + firstLineExceedsLimit: false, + maxLines, + maxBytes + }; + } + const firstLineBytes = utf8ByteLength(lines[0]); + if (firstLineBytes > maxBytes) { + return { + content: "", + truncated: true, + truncatedBy: "bytes", + totalLines, + totalBytes, + outputLines: 0, + outputBytes: 0, + lastLinePartial: false, + firstLineExceedsLimit: true, + maxLines, + maxBytes + }; + } + const outputLinesArr = []; + let outputBytesCount = 0; + let truncatedBy = "lines"; + for (let i = 0; i < lines.length && i < maxLines; i++) { + const line = lines[i]; + const lineBytes = utf8ByteLength(line) + (i > 0 ? 1 : 0); + if (outputBytesCount + lineBytes > maxBytes) { + truncatedBy = "bytes"; + break; + } + outputLinesArr.push(line); + outputBytesCount += lineBytes; + } + if (truncatedBy !== "bytes") + truncatedBy = outputLinesArr.length < totalLines ? "lines" : "bytes"; + const outputContent = outputLinesArr.join("\n"); + const finalOutputBytes = utf8ByteLength(outputContent); + return { + content: outputContent, + truncated: true, + truncatedBy, + totalLines, + totalBytes, + outputLines: outputLinesArr.length, + outputBytes: finalOutputBytes, + lastLinePartial: false, + firstLineExceedsLimit: false, + maxLines, + maxBytes + }; +} + +// node_modules/@earendil-works/pi-durable/dist/harness/define.js +function defineExtension(extension) { + return extension; +} +function defineTool(tool) { + return tool; +} + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path4) { + const ctrl = callVisitor(key, node, visitor, path4); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path4, ctrl); + return visit_(key, ctrl, visitor, path4); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path4 = Object.freeze(path4.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path4); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path4 = Object.freeze(path4.concat(node)); + const ck = visit_("key", node.key, visitor, path4); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path4); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path4) { + const ctrl = await callVisitor(key, node, visitor, path4); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path4, ctrl); + return visitAsync_(key, ctrl, visitor, path4); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path4 = Object.freeze(path4.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path4); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path4 = Object.freeze(path4.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path4); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path4); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path4) { + if (typeof visitor === "function") + return visitor(key, node, path4); + if (isMap(node)) + return visitor.Map?.(key, node, path4); + if (isSeq(node)) + return visitor.Seq?.(key, node, path4); + if (isPair(node)) + return visitor.Pair?.(key, node, path4); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path4); + if (isAlias(node)) + return visitor.Alias?.(key, node, path4); + return void 0; +} +function replaceNode(key, path4, node) { + const parent = path4[path4.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy = new _Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value, arg, ctx) { + if (Array.isArray(value)) + return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value === "bigint" && !ctx?.keep) + return Number(value); + return value; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; +var Scalar = class extends NodeBase { + constructor(value) { + super(SCALAR); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value) && !t.format); +} +function createNode(value, tagName, ctx) { + if (isDocument(value)) + value = value.contents; + if (isNode(value)) + return value; + if (isPair(value)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value); + return map3; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema4.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") { + value = value.toJSON(); + } + if (!value || typeof value !== "object") { + const node2 = new Scalar(value); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path4, value) { + let v = value; + for (let i = path4.length - 1; i >= 0; --i) { + const k = path4[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path4) => path4 == null || typeof path4 === "object" && !!path4[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy.schema = schema4; + copy.items = copy.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path4, value) { + if (isEmptyPath(path4)) + this.add(value); + else { + const [key, ...rest] = path4; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path4) { + const [key, ...rest] = path4; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path4, keepScalar) { + const [key, ...rest] = path4; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path4) { + const [key, ...rest] = path4; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path4, value) { + const [key, ...rest] = path4; + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit3 = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit3) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit3) + return true; + start = i + 1; + if (strLen - start <= limit3) + return false; + } + } + return true; +} +function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) { + return quotedString(value, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str2 = value.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify3(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify3(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value) && !value.flow && !value.tag && !value.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify3(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default); +function addMergeToJSMap(ctx, map3, value) { + const source = resolveAliasValue(ctx, value); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value) { + const source = resolveAliasValue(ctx, value); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value2] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value2); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value2, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value) { + return ctx && isAlias(value) ? value.resolve(ctx.doc, ctx) : value; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value, ctx) { + const k = createNode(key, void 0, ctx); + const v = createNode(value, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value; + } + clone(schema4) { + let { key, value } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value)) + value = value.clone(schema4); + return new _Pair(key, value); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify6 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify6(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify3(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines.push(blockItemPrefix + str3); + } + let str2; + if (lines.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify3(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines.push(str2); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value) => { + if (typeof replacer === "function") + value = replacer.call(obj2, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== void 0 || keepUndefined) + map3.items.push(createPair(key, value, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value] of obj2) + add(key, value); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify(value) { + return typeof value === "bigint" || Number.isInteger(value); +} +var stringifyJSON = ({ value }) => JSON.stringify(value); +var jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value, ctx)); + } + return pairs2; +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value) { + if (typeof value !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === "function") + value = replacer.call(iterable, value, value); + set2.items.push(createPair(value, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +var timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path4) => { + let item = cst; + for (const [field, index] of path4) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path4) => { + const parent = visit2.itemAtPath(cst, path4.slice(0, -1)); + const field = path4[path4.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path4, item, visitor) { + let ctrl = visitor(item, path4); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path4.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path4); + } + } + return typeof ctrl === "function" ? ctrl(item, path4) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); + +// node_modules/@earendil-works/pi-durable/dist/tools/env.js +function requireEnv(api) { + if (api.env === void 0) + throw new Error("No execution environment is configured"); + return api.env; +} + +// node_modules/@earendil-works/pi-durable/dist/tools/bash.js +var MAX_TIMEOUT_SECONDS = 2147483647 / 1e3; +var bashSchema = obj({ + command: str({ description: "Bash command to execute" }), + timeout: opt(num({ description: "Timeout in seconds (optional, no default timeout)" })) +}, { open: true }); +var powershellSchema = obj({ + command: str({ description: "PowerShell command to execute" }), + timeout: opt(num({ description: "Timeout in seconds (optional, no default timeout)" })) +}, { open: true }); +var shellStructuredOutputSchema = obj({ + output: str({ description: "Combined stdout and stderr: the retained tail, as the model sees it" }), + truncated: bool({ description: "Whether earlier output was dropped" }), + fullOutputPath: opt(str({ description: "File with the complete output, when it was spilled" })), + exitCode: num() +}, { open: true }); +function validateTimeout(timeout) { + if (timeout === void 0) + return; + if (!Number.isFinite(timeout) || timeout <= 0) { + throw new Error("Invalid timeout: must be a finite number of seconds"); + } + if (timeout > MAX_TIMEOUT_SECONDS) { + throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`); + } +} +async function prepareExecution(command, options, api, context) { + const execution = { + command: options?.commandPrefix ? `${options.commandPrefix} +${command}` : command, + cwd: requireEnv(api).cwd, + env: {}, + inheritEnv: true + }; + await options?.prepare?.(execution, api, context); + return execution; +} +async function runCommand(commands, execution, timeout, api, context) { + const env = requireEnv(api); + let result; + for (const command of commands) { + result = await env.exec(command, { + cwd: execution.cwd, + env: execution.env, + inheritEnv: execution.inheritEnv, + ...timeout === void 0 ? {} : { timeout }, + onOutput: (text, _context, info) => api.output(text, info.skipped), + spill: { afterBytes: DEFAULT_MAX_BYTES, afterLines: DEFAULT_MAX_LINES }, + // An environment may then omit output outside the retained tail and report the omission. + ...api.outputWindow === void 0 ? {} : { window: api.outputWindow } + }, context); + if (result.ok || result.error.code !== "spawn_error") + break; + } + if (result === void 0) + throw new Error("No command to run"); + const spillPath = result.ok ? result.value.spillPath : result.error.spillPath; + if (spillPath !== void 0) { + api.diagnostic({ severity: "info", code: "full_output", message: `Full output: ${spillPath}` }); + } + if (!result.ok) { + if (result.error.code === "aborted" && context.abortSignal?.aborted) + throw result.error; + if (result.error.code === "timeout") + throw new Error(`Command timed out after ${timeout} seconds`); + if (result.error.code === "aborted") + throw new Error("Command aborted"); + throw result.error; + } + const exitCode = result.value.exitCode; + const retained = api.retainedOutput(); + const structuredOutput = { + output: retained.text, + truncated: retained.truncated, + ...spillPath === void 0 ? {} : { fullOutputPath: spillPath }, + exitCode + }; + if (exitCode === 0) + return { structuredOutput }; + const exited = { severity: "error", code: "exit_code", message: `Command exited with code ${exitCode}` }; + return { structuredOutput, isError: true, diagnostics: [exited] }; +} +function createBashTool(options) { + return defineTool({ + name: "bash", + description: `Execute a bash command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`, + parameters: bashSchema, + structuredOutputSchema: shellStructuredOutputSchema, + outputLimits: { retain: "tail" }, + async execute(args, api, context) { + validateTimeout(args.timeout); + const execution = await prepareExecution(args.command, options, api, context); + return runCommand([execution.command], execution, args.timeout, api, context); + } + }); +} + +// node_modules/diff/libesm/diff/base.js +var Diff = class { + diff(oldStr, newStr, options = {}) { + let callback; + if (typeof options === "function") { + callback = options; + options = {}; + } else if ("callback" in options) { + callback = options.callback; + } + const oldString = this.castInput(oldStr, options); + const newString = this.castInput(newStr, options); + const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); + const newTokens = this.removeEmpty(this.tokenize(newString, options)); + return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); + } + diffWithOptionsObj(oldTokens, newTokens, options, callback) { + var _a6; + const done = (value) => { + value = this.postProcess(value, options); + if (callback) { + setTimeout(function() { + callback(value); + }, 0); + return void 0; + } else { + return value; + } + }; + const newLen = newTokens.length, oldLen = oldTokens.length; + let editLength = 1; + let maxEditLength = newLen + oldLen; + if (options.maxEditLength != null) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + const maxExecutionTime = (_a6 = options.timeout) !== null && _a6 !== void 0 ? _a6 : Infinity; + const abortAfterTimestamp = Date.now() + maxExecutionTime; + const bestPath = [{ oldPos: -1, lastComponent: void 0 }]; + let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); + if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); + } + let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; + const execEditLength = () => { + for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { + let basePath; + const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; + if (removePath) { + bestPath[diagonalPath - 1] = void 0; + } + let canAdd = false; + if (addPath) { + const addPathNewPos = addPath.oldPos - diagonalPath; + canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; + } + const canRemove = removePath && removePath.oldPos + 1 < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = void 0; + continue; + } + if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { + basePath = this.addToPath(addPath, true, false, 0, options); + } else { + basePath = this.addToPath(removePath, false, true, 1, options); + } + newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); + if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { + return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; + } else { + bestPath[diagonalPath] = basePath; + if (basePath.oldPos + 1 >= oldLen) { + maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); + } + if (newPos + 1 >= newLen) { + minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); + } + } + } + editLength++; + }; + if (callback) { + (function exec() { + setTimeout(function() { + if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { + return callback(void 0); + } + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { + const ret = execEditLength(); + if (ret) { + return ret; + } + } + } + } + addToPath(path4, added, removed, oldPosInc, options) { + const last = path4.lastComponent; + if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { + return { + oldPos: path4.oldPos + oldPosInc, + lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent } + }; + } else { + return { + oldPos: path4.oldPos + oldPosInc, + lastComponent: { count: 1, added, removed, previousComponent: last } + }; + } + } + extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { + const newLen = newTokens.length, oldLen = oldTokens.length; + let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { + newPos++; + oldPos++; + commonCount++; + if (options.oneChangePerToken) { + basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; + } + } + if (commonCount && !options.oneChangePerToken) { + basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; + } + basePath.oldPos = oldPos; + return newPos; + } + equals(left, right, options) { + if (options.comparator) { + return options.comparator(left, right); + } else { + return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + } + removeEmpty(array) { + const ret = []; + for (let i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + castInput(value, options) { + return value; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + tokenize(value, options) { + return Array.from(value); + } + join(chars) { + return chars.join(""); + } + postProcess(changeObjects, options) { + return changeObjects; + } + get useLongestToken() { + return false; + } + buildValues(lastComponent, newTokens, oldTokens) { + const components = []; + let nextComponent; + while (lastComponent) { + components.push(lastComponent); + nextComponent = lastComponent.previousComponent; + delete lastComponent.previousComponent; + lastComponent = nextComponent; + } + components.reverse(); + const componentLen = components.length; + let componentPos = 0, newPos = 0, oldPos = 0; + for (; componentPos < componentLen; componentPos++) { + const component = components[componentPos]; + if (!component.removed) { + if (!component.added && this.useLongestToken) { + let value = newTokens.slice(newPos, newPos + component.count); + value = value.map(function(value2, i) { + const oldValue = oldTokens[oldPos + i]; + return oldValue.length > value2.length ? oldValue : value2; + }); + component.value = this.join(value); + } else { + component.value = this.join(newTokens.slice(newPos, newPos + component.count)); + } + newPos += component.count; + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); + oldPos += component.count; + } + } + return components; + } +}; + +// node_modules/diff/libesm/diff/line.js +var LineDiff = class extends Diff { + constructor() { + super(...arguments); + this.tokenize = tokenize2; + } + equals(left, right, options) { + if (options.ignoreWhitespace) { + if (!options.newlineIsToken || !left.includes("\n")) { + left = left.trim(); + } + if (!options.newlineIsToken || !right.includes("\n")) { + right = right.trim(); + } + } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { + if (left.endsWith("\n")) { + left = left.slice(0, -1); + } + if (right.endsWith("\n")) { + right = right.slice(0, -1); + } + } + return super.equals(left, right, options); + } +}; +var lineDiff = new LineDiff(); +function diffLines(oldStr, newStr, options) { + return lineDiff.diff(oldStr, newStr, options); +} +function tokenize2(value, options) { + if (options.stripTrailingCr) { + value = value.replace(/\r\n/g, "\n"); + } + const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } + for (let i = 0; i < linesAndNewlines.length; i++) { + const line = linesAndNewlines[i]; + if (i % 2 && !options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + retLines.push(line); + } + } + return retLines; +} + +// node_modules/diff/libesm/patch/create.js +var INCLUDE_HEADERS = { + includeIndex: true, + includeUnderline: true, + includeFileHeaders: true +}; +var FILE_HEADERS_ONLY = { + includeIndex: false, + includeUnderline: false, + includeFileHeaders: true +}; +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + let optionsObj; + if (!options) { + optionsObj = {}; + } else if (typeof options === "function") { + optionsObj = { callback: options }; + } else { + optionsObj = options; + } + if (typeof optionsObj.context === "undefined") { + optionsObj.context = 4; + } + const context = optionsObj.context; + if (optionsObj.newlineIsToken) { + throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions"); + } + if (!optionsObj.callback) { + return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); + } else { + const { callback } = optionsObj; + diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => { + const patch = diffLinesResultToPatch(diff); + callback(patch); + } })); + } + function diffLinesResultToPatch(diff) { + if (!diff) { + return; + } + diff.push({ value: "", lines: [] }); + function contextLines(lines) { + return lines.map(function(entry) { + return " " + entry; + }); + } + const hunks = []; + let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; + for (let i = 0; i < diff.length; i++) { + const current = diff[i], lines = current.lines || splitLines(current.value); + current.lines = lines; + if (current.added || current.removed) { + if (!oldRangeStart) { + const prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + if (prev) { + curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + for (const line of lines) { + curRange.push((current.added ? "+" : "-") + line); + } + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + if (oldRangeStart) { + if (lines.length <= context * 2 && i < diff.length - 2) { + for (const line of contextLines(lines)) { + curRange.push(line); + } + } else { + const contextSize = Math.min(lines.length, context); + for (const line of contextLines(lines.slice(0, contextSize))) { + curRange.push(line); + } + const hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + } + for (const hunk of hunks) { + for (let i = 0; i < hunk.lines.length; i++) { + if (hunk.lines[i].endsWith("\n")) { + hunk.lines[i] = hunk.lines[i].slice(0, -1); + } else { + hunk.lines.splice(i + 1, 0, "\\ No newline at end of file"); + i++; + } + } + } + return { + oldFileName, + newFileName, + oldHeader, + newHeader, + hunks + }; + } +} +function formatPatch(patch, headerOptions) { + if (!headerOptions) { + headerOptions = INCLUDE_HEADERS; + } + if (Array.isArray(patch)) { + if (patch.length > 1 && !headerOptions.includeFileHeaders) { + throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)"); + } + return patch.map((p) => formatPatch(p, headerOptions)).join("\n"); + } + const ret = []; + if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { + ret.push("Index: " + patch.oldFileName); + } + if (headerOptions.includeUnderline) { + ret.push("==================================================================="); + } + if (headerOptions.includeFileHeaders) { + ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader)); + ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader)); + } + for (let i = 0; i < patch.hunks.length; i++) { + const hunk = patch.hunks[i]; + if (hunk.oldLines === 0) { + hunk.oldStart -= 1; + } + if (hunk.newLines === 0) { + hunk.newStart -= 1; + } + ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@"); + for (const line of hunk.lines) { + ret.push(line); + } + } + return ret.join("\n") + "\n"; +} +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (typeof options === "function") { + options = { callback: options }; + } + if (!(options === null || options === void 0 ? void 0 : options.callback)) { + const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + if (!patchObj) { + return; + } + return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); + } else { + const { callback } = options; + structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => { + if (!patchObj) { + callback(void 0); + } else { + callback(formatPatch(patchObj, options.headerOptions)); + } + } })); + } +} +function splitLines(text) { + const hasTrailingNl = text.endsWith("\n"); + const result = text.split("\n").map((line) => line + "\n"); + if (hasTrailingNl) { + result.pop(); + } else { + result.push(result.pop().slice(0, -1)); + } + return result; +} + +// node_modules/@earendil-works/pi-durable/dist/tools/edit-diff.js +function detectLineEnding(content) { + const crlfIdx = content.indexOf("\r\n"); + const lfIdx = content.indexOf("\n"); + if (lfIdx === -1) + return "\n"; + if (crlfIdx === -1) + return "\n"; + return crlfIdx < lfIdx ? "\r\n" : "\n"; +} +function normalizeToLF(text) { + return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); +} +function restoreLineEndings(text, ending) { + return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text; +} +function normalizeForFuzzyMatch(text) { + return text.normalize("NFKC").split("\n").map((line) => line.trimEnd()).join("\n").replace(/[\u2018\u2019\u201A\u201B]/g, "'").replace(/[\u201C\u201D\u201E\u201F]/g, '"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g, "-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " "); +} +function splitLinesWithEndings(content) { + return content.match(/[^\n]*\n|[^\n]+/g) ?? []; +} +function getLineSpans(content) { + let offset = 0; + return splitLinesWithEndings(content).map((line) => { + const span = { start: offset, end: offset + line.length }; + offset = span.end; + return span; + }); +} +function getReplacementLineRange(lines, replacement) { + const replacementStart = replacement.matchIndex; + const replacementEnd = replacement.matchIndex + replacement.matchLength; + let startLine = -1; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (replacementStart >= line.start && replacementStart < line.end) { + startLine = i; + break; + } + } + if (startLine === -1) { + throw new Error("Replacement range is outside the base content."); + } + let endLine = startLine; + while (endLine < lines.length && lines[endLine].end < replacementEnd) { + endLine++; + } + if (endLine >= lines.length) { + throw new Error("Replacement range is outside the base content."); + } + return { startLine, endLine: endLine + 1 }; +} +function applyReplacements(content, replacements, offset = 0) { + let result = content; + for (let i = replacements.length - 1; i >= 0; i--) { + const replacement = replacements[i]; + const matchIndex = replacement.matchIndex - offset; + result = result.substring(0, matchIndex) + replacement.newText + result.substring(matchIndex + replacement.matchLength); + } + return result; +} +function applyReplacementsPreservingUnchangedLines(originalContent, baseContent, replacements) { + const originalLines = splitLinesWithEndings(originalContent); + const baseLines = getLineSpans(baseContent); + if (originalLines.length !== baseLines.length) { + throw new Error("Cannot preserve unchanged lines because the base content has a different line count."); + } + const groups = []; + const sortedReplacements = [...replacements].sort((a, b) => a.matchIndex - b.matchIndex); + for (const replacement of sortedReplacements) { + const range = getReplacementLineRange(baseLines, replacement); + const current = groups[groups.length - 1]; + if (current && range.startLine < current.endLine) { + current.endLine = Math.max(current.endLine, range.endLine); + current.replacements.push(replacement); + continue; + } + groups.push({ ...range, replacements: [replacement] }); + } + let originalLineIndex = 0; + let result = ""; + for (const group of groups) { + result += originalLines.slice(originalLineIndex, group.startLine).join(""); + const groupStartOffset = baseLines[group.startLine].start; + const groupEndOffset = baseLines[group.endLine - 1].end; + result += applyReplacements(baseContent.slice(groupStartOffset, groupEndOffset), group.replacements, groupStartOffset); + originalLineIndex = group.endLine; + } + result += originalLines.slice(originalLineIndex).join(""); + return result; +} +function fuzzyFindText(content, oldText) { + const exactIndex = content.indexOf(oldText); + if (exactIndex !== -1) { + return { + found: true, + index: exactIndex, + matchLength: oldText.length, + usedFuzzyMatch: false, + contentForReplacement: content + }; + } + const fuzzyContent = normalizeForFuzzyMatch(content); + const fuzzyOldText = normalizeForFuzzyMatch(oldText); + const fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText); + if (fuzzyIndex === -1) { + return { + found: false, + index: -1, + matchLength: 0, + usedFuzzyMatch: false, + contentForReplacement: content + }; + } + return { + found: true, + index: fuzzyIndex, + matchLength: fuzzyOldText.length, + usedFuzzyMatch: true, + contentForReplacement: fuzzyContent + }; +} +function stripBom(content) { + return content.startsWith("\uFEFF") ? { bom: "\uFEFF", text: content.slice(1) } : { bom: "", text: content }; +} +function countOccurrences(content, oldText) { + const fuzzyContent = normalizeForFuzzyMatch(content); + const fuzzyOldText = normalizeForFuzzyMatch(oldText); + return fuzzyContent.split(fuzzyOldText).length - 1; +} +function getNotFoundError(path4, editIndex, totalEdits) { + if (totalEdits === 1) { + return new Error(`Could not find the exact text in ${path4}. The old text must match exactly including all whitespace and newlines.`); + } + return new Error(`Could not find edits[${editIndex}] in ${path4}. The oldText must match exactly including all whitespace and newlines.`); +} +function getDuplicateError(path4, editIndex, totalEdits, occurrences) { + if (totalEdits === 1) { + return new Error(`Found ${occurrences} occurrences of the text in ${path4}. The text must be unique. Please provide more context to make it unique.`); + } + return new Error(`Found ${occurrences} occurrences of edits[${editIndex}] in ${path4}. Each oldText must be unique. Please provide more context to make it unique.`); +} +function getEmptyOldTextError(path4, editIndex, totalEdits) { + if (totalEdits === 1) { + return new Error(`oldText must not be empty in ${path4}.`); + } + return new Error(`edits[${editIndex}].oldText must not be empty in ${path4}.`); +} +function getNoChangeError(path4, totalEdits) { + if (totalEdits === 1) { + return new Error(`No changes made to ${path4}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`); + } + return new Error(`No changes made to ${path4}. The replacements produced identical content.`); +} +function applyEditsToNormalizedContent(normalizedContent, edits, path4) { + const normalizedEdits = edits.map((edit) => ({ + oldText: normalizeToLF(edit.oldText), + newText: normalizeToLF(edit.newText) + })); + for (let i = 0; i < normalizedEdits.length; i++) { + if (normalizedEdits[i].oldText.length === 0) { + throw getEmptyOldTextError(path4, i, normalizedEdits.length); + } + } + const initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText)); + const usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch); + const replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent; + const matchedEdits = []; + for (let i = 0; i < normalizedEdits.length; i++) { + const edit = normalizedEdits[i]; + const matchResult = fuzzyFindText(replacementBaseContent, edit.oldText); + if (!matchResult.found) { + throw getNotFoundError(path4, i, normalizedEdits.length); + } + const occurrences = countOccurrences(replacementBaseContent, edit.oldText); + if (occurrences > 1) { + throw getDuplicateError(path4, i, normalizedEdits.length, occurrences); + } + matchedEdits.push({ + editIndex: i, + matchIndex: matchResult.index, + matchLength: matchResult.matchLength, + newText: edit.newText + }); + } + matchedEdits.sort((a, b) => a.matchIndex - b.matchIndex); + for (let i = 1; i < matchedEdits.length; i++) { + const previous = matchedEdits[i - 1]; + const current = matchedEdits[i]; + if (previous.matchIndex + previous.matchLength > current.matchIndex) { + throw new Error(`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path4}. Merge them into one edit or target disjoint regions.`); + } + } + const baseContent = normalizedContent; + const newContent = usedFuzzyMatch ? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits) : applyReplacements(replacementBaseContent, matchedEdits); + if (baseContent === newContent) { + throw getNoChangeError(path4, normalizedEdits.length); + } + return { baseContent, newContent }; +} +function generateUnifiedPatch(path4, oldContent, newContent, contextLines = 4) { + return createTwoFilesPatch(path4, path4, oldContent, newContent, void 0, void 0, { + context: contextLines, + headerOptions: FILE_HEADERS_ONLY + }); +} +function generateDiffString(oldContent, newContent, contextLines = 4) { + const parts = diffLines(oldContent, newContent); + const output = []; + const oldLines = oldContent.split("\n"); + const newLines = newContent.split("\n"); + const maxLineNum = Math.max(oldLines.length, newLines.length); + const lineNumWidth = String(maxLineNum).length; + let oldLineNum = 1; + let newLineNum = 1; + let lastWasChange = false; + let firstChangedLine; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + const raw = part.value.split("\n"); + if (raw[raw.length - 1] === "") { + raw.pop(); + } + if (part.added || part.removed) { + if (firstChangedLine === void 0) { + firstChangedLine = newLineNum; + } + for (const line of raw) { + if (part.added) { + const lineNum = String(newLineNum).padStart(lineNumWidth, " "); + output.push(`+${lineNum} ${line}`); + newLineNum++; + } else { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(`-${lineNum} ${line}`); + oldLineNum++; + } + } + lastWasChange = true; + } else { + const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed); + const hasLeadingChange = lastWasChange; + const hasTrailingChange = nextPartIsChange; + if (hasLeadingChange && hasTrailingChange) { + if (raw.length <= contextLines * 2) { + for (const line of raw) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + } else { + const leadingLines = raw.slice(0, contextLines); + const trailingLines = raw.slice(raw.length - contextLines); + const skippedLines = raw.length - leadingLines.length - trailingLines.length; + for (const line of leadingLines) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + output.push(` ${"".padStart(lineNumWidth, " ")} ...`); + oldLineNum += skippedLines; + newLineNum += skippedLines; + for (const line of trailingLines) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + } + } else if (hasLeadingChange) { + const shownLines = raw.slice(0, contextLines); + const skippedLines = raw.length - shownLines.length; + for (const line of shownLines) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + if (skippedLines > 0) { + output.push(` ${"".padStart(lineNumWidth, " ")} ...`); + oldLineNum += skippedLines; + newLineNum += skippedLines; + } + } else if (hasTrailingChange) { + const skippedLines = Math.max(0, raw.length - contextLines); + if (skippedLines > 0) { + output.push(` ${"".padStart(lineNumWidth, " ")} ...`); + oldLineNum += skippedLines; + newLineNum += skippedLines; + } + for (const line of raw.slice(skippedLines)) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + } else { + oldLineNum += raw.length; + newLineNum += raw.length; + } + lastWasChange = false; + } + } + return { diff: output.join("\n"), firstChangedLine }; +} + +// node_modules/@earendil-works/pi-durable/dist/env/decode.js +function rangeDecoder() { + return new TextDecoder("utf-8", { ignoreBOM: true }); +} +function startsWithBom(firstBytes) { + return firstBytes[0] === 239 && firstBytes[1] === 187 && firstBytes[2] === 191; +} + +// node_modules/@earendil-works/pi-durable/dist/env/index.js +function getOrThrow(result) { + if (!result.ok) + throw result.error; + return result.value; +} + +// node_modules/@earendil-works/pi-durable/dist/tools/file-mutation-queue.js +var queues = /* @__PURE__ */ new Map(); +async function mutationKey(env, path4, context) { + const absolutePath = getOrThrow(await env.absolutePath(path4, context)); + return `${env.id}\0${await canonical(env, absolutePath, context)}`; +} +async function canonical(env, absolutePath, context) { + const result = await env.canonicalPath(absolutePath, context); + if (result.ok) + return result.value; + if (result.error.code === "not_supported") + return absolutePath; + if (result.error.code !== "not_found") + throw result.error; + const parent = getOrThrow(await env.joinPath([absolutePath, ".."], context)); + if (parent === absolutePath || !absolutePath.startsWith(parent)) + return absolutePath; + const name = absolutePath.slice(parent.length + (/[/\\]$/.test(parent) ? 0 : 1)); + return getOrThrow(await env.joinPath([await canonical(env, parent, context), name], context)); +} +async function withFileMutationQueue(env, path4, fn, context) { + const key = await mutationKey(env, path4, context); + const previous = queues.get(key) ?? Promise.resolve(); + let release = () => { + }; + const done = new Promise((resolve) => { + release = resolve; + }); + const tail = previous.then(() => done); + queues.set(key, tail); + await previous; + try { + return await fn(); + } finally { + release(); + if (queues.get(key) === tail) + queues.delete(key); + } +} + +// node_modules/@earendil-works/pi-durable/dist/tools/path-utils.js +var UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g; +var NARROW_NO_BREAK_SPACE = "\u202F"; +function normalizeToolPath(path4) { + const normalized = path4.replace(UNICODE_SPACES, " "); + return normalized.startsWith("@") ? normalized.slice(1) : normalized; +} +async function resolveToolPath(env, path4, context) { + return getOrThrow(await env.absolutePath(normalizeToolPath(path4), context)); +} +async function resolveReadToolPath(env, path4, context) { + const resolved = await resolveToolPath(env, path4, context); + const variants = [ + resolved, + resolved.replace(/ (AM|PM)\./gi, `${NARROW_NO_BREAK_SPACE}$1.`), + resolved.normalize("NFD"), + resolved.replace(/'/g, "\u2019"), + resolved.normalize("NFD").replace(/'/g, "\u2019") + ]; + for (const variant of new Set(variants)) { + if (getOrThrow(await env.exists(variant, context))) + return variant; + } + return resolved; +} + +// node_modules/@earendil-works/pi-durable/dist/tools/edit.js +var replaceEditSchema = obj({ + oldText: str({ + description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call." + }), + newText: str({ description: "Replacement text for this targeted edit." }) +}, { open: true }); +var editSchema = obj({ + path: str({ description: "Path to the file to edit (relative or absolute)" }), + edits: arr(replaceEditSchema, { + description: "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead." + }) +}, { open: true }); +function isSingleEditInput(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) + return false; + const edit = value; + return typeof edit.oldText === "string" && typeof edit.newText === "string"; +} +function prepareEditArguments(input) { + if (!input || typeof input !== "object" || Array.isArray(input)) + return input; + const args = { ...input }; + if (typeof args.edits === "string") { + try { + const parsed = JSON.parse(args.edits); + if (Array.isArray(parsed)) { + args.edits = parsed; + } else if (isSingleEditInput(parsed)) { + args.edits = [parsed]; + } + } catch { + } + } else if (isSingleEditInput(args.edits)) { + args.edits = [args.edits]; + } + const legacy = args; + if (typeof legacy.oldText !== "string" || typeof legacy.newText !== "string") + return legacy; + const edits = Array.isArray(legacy.edits) ? [...legacy.edits] : []; + edits.push({ oldText: legacy.oldText, newText: legacy.newText }); + const { oldText: _oldText, newText: _newText, ...rest } = legacy; + return { ...rest, edits }; +} +function validateEditInput(input) { + if (!Array.isArray(input.edits) || input.edits.length === 0) { + throw new Error("Edit tool input is invalid. edits must contain at least one replacement."); + } + return { path: input.path, edits: input.edits }; +} +function editAccessError(path4, error) { + return new Error(`Could not edit file: ${path4}. Error code: ${error.code}.`, { cause: error }); +} +function createEditTool() { + return defineTool({ + name: "edit", + description: "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.", + parameters: editSchema, + prepareArguments: prepareEditArguments, + async execute(args, api, context) { + const { path: path4, edits } = validateEditInput(args); + const env = requireEnv(api); + const absolutePath = await resolveToolPath(env, path4, context); + return withFileMutationQueue(env, absolutePath, async () => { + if (context.abortSignal?.aborted) + throw new Error("Operation aborted"); + const info = await env.fileInfo(absolutePath, context); + if (!info.ok) + throw editAccessError(path4, info.error); + if (info.value.kind !== "file" && info.value.kind !== "symlink") { + throw new Error(`Could not edit file: ${path4}. Path is not a file.`); + } + const readResult = await env.readTextFile(absolutePath, context); + if (!readResult.ok) + throw editAccessError(path4, readResult.error); + if (context.abortSignal?.aborted) + throw new Error("Operation aborted"); + const { bom, text: content } = stripBom(readResult.value); + const originalEnding = detectLineEnding(content); + const normalizedContent = normalizeToLF(content); + const { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path4); + if (context.abortSignal?.aborted) + throw new Error("Operation aborted"); + const finalContent = bom + restoreLineEndings(newContent, originalEnding); + const writeResult = await env.writeFile(absolutePath, finalContent, context); + if (!writeResult.ok) + throw editAccessError(path4, writeResult.error); + if (context.abortSignal?.aborted) + throw new Error("Operation aborted"); + const diffResult = generateDiffString(baseContent, newContent); + const details = { + diff: diffResult.diff, + patch: generateUnifiedPatch(path4, baseContent, newContent), + ...diffResult.firstChangedLine === void 0 ? {} : { firstChangedLine: diffResult.firstChangedLine } + }; + return { + output: [{ type: "text", text: `Successfully replaced ${edits.length} block(s) in ${path4}.` }], + details + }; + }, context); + } + }); +} + +// node_modules/@earendil-works/pi-durable/dist/tools/image.js +var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]; +var HEADER_BYTES = 32; +var BLOCK_BYTES = 64 * 1024; +async function detectSupportedImageMimeTypeOf(source) { + const header = await source.read(0, HEADER_BYTES); + if (!startsWith(header, PNG_SIGNATURE)) + return detectSupportedImageMimeType(header); + return isPng(header) && !await isAnimatedPngOf(source) ? "image/png" : void 0; +} +async function isAnimatedPngOf(source) { + let block = new Uint8Array(0); + let blockStart = 0; + const bytesAt = async (offset2, length) => { + if (offset2 < blockStart || offset2 + length > blockStart + block.length) { + blockStart = offset2; + block = await source.read(offset2, BLOCK_BYTES); + } + return block.subarray(offset2 - blockStart, offset2 - blockStart + length); + }; + let offset = PNG_SIGNATURE.length; + while (offset + 8 <= source.size) { + const chunkHeader = await bytesAt(offset, 8); + const chunkLength = readUint32BE(chunkHeader, 0); + if (startsWithAscii(chunkHeader, 4, "acTL")) + return true; + if (startsWithAscii(chunkHeader, 4, "IDAT")) + return false; + const nextOffset = offset + 8 + chunkLength + 4; + if (nextOffset <= offset || nextOffset > source.size) + return false; + offset = nextOffset; + } + return false; +} +function detectSupportedImageMimeType(buffer) { + if (startsWith(buffer, [255, 216, 255])) + return buffer[3] === 247 ? void 0 : "image/jpeg"; + if (startsWith(buffer, PNG_SIGNATURE)) + return isPng(buffer) && !isAnimatedPng(buffer) ? "image/png" : void 0; + if (startsWithAscii(buffer, 0, "GIF87a") || startsWithAscii(buffer, 0, "GIF89a")) + return "image/gif"; + if (startsWithAscii(buffer, 0, "RIFF") && startsWithAscii(buffer, 8, "WEBP")) + return "image/webp"; + if (startsWithAscii(buffer, 0, "BM") && isBmp(buffer)) + return "image/bmp"; + return void 0; +} +function isPng(buffer) { + return buffer.length >= 16 && readUint32BE(buffer, PNG_SIGNATURE.length) === 13 && startsWithAscii(buffer, 12, "IHDR"); +} +function isAnimatedPng(buffer) { + let offset = PNG_SIGNATURE.length; + while (offset + 8 <= buffer.length) { + const chunkLength = readUint32BE(buffer, offset); + const chunkTypeOffset = offset + 4; + if (startsWithAscii(buffer, chunkTypeOffset, "acTL")) + return true; + if (startsWithAscii(buffer, chunkTypeOffset, "IDAT")) + return false; + const nextOffset = offset + 8 + chunkLength + 4; + if (nextOffset <= offset || nextOffset > buffer.length) + return false; + offset = nextOffset; + } + return false; +} +function imageDimensions(bytes2, mimeType) { + switch (mimeType) { + case "image/png": + return bytes2.length < 24 ? void 0 : { width: readUint32BE(bytes2, 16), height: readUint32BE(bytes2, 20) }; + case "image/gif": + return bytes2.length < 10 ? void 0 : { width: readUint16LE(bytes2, 6), height: readUint16LE(bytes2, 8) }; + case "image/webp": + if (bytes2.length < 30) + return void 0; + if (startsWithAscii(bytes2, 12, "VP8 ")) + return { width: readUint16LE(bytes2, 26) & 16383, height: readUint16LE(bytes2, 28) & 16383 }; + if (startsWithAscii(bytes2, 12, "VP8L")) { + const bits = readUint32LE(bytes2, 21); + return { width: (bits & 16383) + 1, height: (bits >>> 14 & 16383) + 1 }; + } + if (startsWithAscii(bytes2, 12, "VP8X")) { + const uint24 = (offset) => readUint16LE(bytes2, offset) + ((bytes2[offset + 2] ?? 0) << 16); + return { width: uint24(24) + 1, height: uint24(27) + 1 }; + } + return void 0; + case "image/jpeg": + for (let offset = 2; offset + 9 <= bytes2.length; ) { + if (bytes2[offset] !== 255) + return void 0; + const marker = bytes2[offset + 1]; + if (marker === 255) { + offset++; + continue; + } + if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) { + return { width: readUint16BE(bytes2, offset + 7), height: readUint16BE(bytes2, offset + 5) }; + } + offset += 2 + readUint16BE(bytes2, offset + 2); + } + return void 0; + default: + return void 0; + } +} +function isBmp(buffer) { + if (buffer.length < 26) + return false; + const declaredFileSize = readUint32LE(buffer, 2); + const pixelDataOffset = readUint32LE(buffer, 10); + const dibHeaderSize = readUint32LE(buffer, 14); + if (declaredFileSize !== 0 && declaredFileSize < 26) + return false; + if (pixelDataOffset < 14 + dibHeaderSize) + return false; + if (declaredFileSize !== 0 && pixelDataOffset >= declaredFileSize) + return false; + let colorPlanes; + let bitsPerPixel; + if (dibHeaderSize === 12) { + colorPlanes = readUint16LE(buffer, 22); + bitsPerPixel = readUint16LE(buffer, 24); + } else if (dibHeaderSize >= 40 && dibHeaderSize <= 124) { + if (buffer.length < 30) + return false; + colorPlanes = readUint16LE(buffer, 26); + bitsPerPixel = readUint16LE(buffer, 28); + } else { + return false; + } + return colorPlanes === 1 && [1, 4, 8, 16, 24, 32].includes(bitsPerPixel); +} +function readUint16LE(buffer, offset) { + return (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8); +} +function readUint16BE(buffer, offset) { + return ((buffer[offset] ?? 0) << 8) + (buffer[offset + 1] ?? 0); +} +function readUint32BE(buffer, offset) { + return (buffer[offset] ?? 0) * 16777216 + ((buffer[offset + 1] ?? 0) << 16) + ((buffer[offset + 2] ?? 0) << 8) + (buffer[offset + 3] ?? 0); +} +function readUint32LE(buffer, offset) { + return (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8) + ((buffer[offset + 2] ?? 0) << 16) + (buffer[offset + 3] ?? 0) * 16777216; +} +function startsWith(buffer, bytes2) { + if (buffer.length < bytes2.length) + return false; + return bytes2.every((byte, index) => buffer[index] === byte); +} +function startsWithAscii(buffer, offset, text) { + if (buffer.length < offset + text.length) + return false; + for (let index = 0; index < text.length; index++) { + if (buffer[offset + index] !== text.charCodeAt(index)) + return false; + } + return true; +} + +// node_modules/@earendil-works/pi-durable/dist/tools/image-processor.js +var DEFAULT_IMAGE_LIMITS = { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4.5 * 1024 * 1024 }; +var INLINE_IMAGE_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]); +function toBase64(bytes2) { + const parts = []; + for (let i = 0; i < bytes2.length; i += 8192) { + parts.push(String.fromCharCode.apply(null, bytes2.subarray(i, i + 8192))); + } + return btoa(parts.join("")); +} +function base64Length(byteLength) { + return Math.ceil(byteLength / 3) * 4; +} + +// node_modules/@earendil-works/pi-durable/dist/tools/read.js +var readSchema = obj({ + path: str({ description: "Path to the file to read (relative or absolute)" }), + offset: opt(num({ description: "Line number to start reading from (1-indexed)" })), + limit: opt(num({ description: "Maximum number of lines to read" })) +}, { open: true }); +var readStructuredOutputSchema = union([ + str(), + obj({ type: lit("image"), data: str(), mimeType: str() }, { open: true }) +]); +var READ_CHUNK = 64 * 1024; +function sliceIndex(value) { + return Number.isNaN(value) ? 0 : Math.trunc(value); +} +async function readHead(reader, start, end, skipBom, context) { + const decoder3 = rangeDecoder(); + let text = ""; + let newlines = 0; + for (let position = skipBom && start === 0 ? 3 : start; position < end; ) { + const bytes2 = getOrThrow(await reader.read(position, Math.min(READ_CHUNK, end - position), context)); + if (bytes2.length === 0) + break; + position += bytes2.length; + const decoded = decoder3.decode(bytes2, { stream: true }); + text += decoded; + for (let index = decoded.indexOf("\n"); index !== -1; index = decoded.indexOf("\n", index + 1)) + newlines++; + if (newlines >= DEFAULT_MAX_LINES || utf8ByteLength(text) > DEFAULT_MAX_BYTES + 1) + return text; + } + return text + decoder3.decode(); +} +function createReadTool(options = {}) { + const formats = options.images === void 0 ? "jpg, png, gif, webp" : "jpg, png, gif, webp, bmp"; + return defineTool({ + name: "read", + description: `Read the contents of a file. Supports text files and images (${formats}). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`, + parameters: readSchema, + structuredOutputSchema: readStructuredOutputSchema, + async execute(args, api, context) { + const { path: path4, offset, limit: limit3 } = args; + const env = requireEnv(api); + const absolutePath = await resolveReadToolPath(env, path4, context); + const reader = getOrThrow(await env.openBinaryReader(absolutePath, void 0, context)); + try { + for (let attempt = 0; ; attempt++) { + const before = getOrThrow(await reader.info(context)); + const mimeType = await detectSupportedImageMimeTypeOf({ + size: before.size, + read: async (position, length) => getOrThrow(await reader.read(position, length, context)) + }); + const result = mimeType === void 0 ? await readText(reader, path4, offset, limit3, context) : await readImage(reader, before, path4, mimeType, options.images, await imageModel(api, context), context); + const after = getOrThrow(await reader.info(context)); + const unchanged = after.size === before.size && after.mtimeMs === before.mtimeMs; + if (unchanged || mimeType === void 0 && after.size > before.size) + return result; + if (attempt === 1) + throw new Error(`${path4} changed while it was read`); + } + } finally { + await reader.close(context); + } + } + }); +} +async function readImage(reader, info, path4, mimeType, processor, { vision, limits }, context) { + let image; + const notes = []; + if (processor !== void 0) { + const bytes2 = getOrThrow(await reader.read(0, info.size, context)); + const prepared = await processor.prepare(bytes2, mimeType, limits); + if (prepared === void 0) + return imageError(`${path4} is an image (${mimeType}) that cannot be prepared for the model`); + image = prepared; + if (prepared.convertedFrom !== void 0) + notes.push(`Converted from ${prepared.convertedFrom} to ${prepared.mimeType}.`); + if (prepared.resized !== void 0) { + const { from, to } = prepared.resized; + const scale = (from.width / to.width).toFixed(2); + notes.push(`Resized from ${from.width}x${from.height} to ${to.width}x${to.height}. Multiply coordinates by ${scale} to map them to the original.`); + } + } else { + if (!INLINE_IMAGE_TYPES.has(mimeType)) { + return imageError(`${path4} is an image (${mimeType}) that needs converting, and no image processor is configured`); + } + const unshrinkable = "and no image processor is configured to shrink it"; + if (base64Length(info.size) > limits.maxBytes) { + return imageError(`${path4} is an image (${mimeType}) of ${formatSize(info.size)}, too large to send, ${unshrinkable}`); + } + const bytes2 = getOrThrow(await reader.read(0, info.size, context)); + const size = imageDimensions(bytes2, mimeType); + if (size === void 0) + return imageError(`${path4} is an image (${mimeType}) whose size cannot be read`); + if (size.width > limits.maxWidth || size.height > limits.maxHeight) { + return imageError(`${path4} is an image (${mimeType}) of ${size.width}x${size.height}, larger than ${limits.maxWidth}x${limits.maxHeight}, ${unshrinkable}`); + } + image = { data: toBase64(bytes2), mimeType }; + } + if (!vision) + notes.push("The current model does not support images; it sees a placeholder instead."); + const diagnostics = [ + { severity: "info", code: "image", message: [`Read image file [${image.mimeType}].`, ...notes].join(" ") } + ]; + const block = { type: "image", data: image.data, mimeType: image.mimeType }; + return { output: [block], structuredOutput: block, diagnostics }; +} +async function imageModel(api, context) { + const ref = (await api.agent(context)).model; + const model2 = ref === void 0 ? void 0 : api.models.getModel(ref.provider, ref.modelId); + const resize = model2?.inputLimits?.images?.resize; + return { + vision: model2?.input.includes("image") ?? true, + limits: { + maxWidth: resize?.maxWidth ?? DEFAULT_IMAGE_LIMITS.maxWidth, + maxHeight: resize?.maxHeight ?? DEFAULT_IMAGE_LIMITS.maxHeight, + maxBytes: resize?.maxBytes ?? DEFAULT_IMAGE_LIMITS.maxBytes + } + }; +} +function imageError(message) { + return { output: [], isError: true, diagnostics: [{ severity: "error", code: "unsupported_image", message }] }; +} +async function readText(reader, path4, offset, limit3, context) { + const startLine = offset ? Math.max(0, offset - 1) : 0; + const startLineDisplay = startLine + 1; + const sliceStart = sliceIndex(startLine); + const scanStart = Number.isSafeInteger(sliceStart) ? sliceStart : 0; + const requestedEnd = limit3 === void 0 ? void 0 : Math.max(scanStart + 1, sliceIndex(startLine + limit3)); + const scanEnd = requestedEnd !== void 0 && Number.isSafeInteger(requestedEnd) ? requestedEnd : void 0; + const scanOf = async (endLine) => getOrThrow(await reader.scanLines({ startLine: scanStart, ...endLine === void 0 ? {} : { endLine } }, context)); + let scan = await scanOf(scanEnd); + const totalFileLines = scan.newlines + 1; + if (startLine >= totalFileLines) { + throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`); + } + let userLimitedLines; + let selectedLineCount = totalFileLines - sliceStart; + if (limit3 !== void 0) { + const endLine = Math.min(startLine + limit3, totalFileLines); + userLimitedLines = endLine - startLine; + const relativeEnd = sliceIndex(endLine); + const sliceEnd = relativeEnd < 0 ? Math.max(totalFileLines + relativeEnd, 0) : relativeEnd; + selectedLineCount = Math.max(0, sliceEnd - sliceStart); + if (selectedLineCount > 0 && relativeEnd < 0) + scan = await scanOf(sliceEnd); + } + const empty2 = selectedLineCount === 0; + const endsWithNewline = !empty2 && scan.lastLineStart === scan.end && scan.lastLineStart > scan.start; + const totals = { + lines: empty2 || scan.selectedBytes === 0 ? 0 : selectedLineCount - (endsWithNewline ? 1 : 0), + bytes: empty2 ? 0 : scan.selectedBytes + }; + const firstBytes = getOrThrow(await reader.read(0, 3, context)); + const head = empty2 ? "" : await readHead(reader, scan.start, scan.end, startsWithBom(firstBytes), context); + const { content: headText, ...truncation } = truncateHeadOf(head, totals); + const diagnostics = []; + let outputText = headText; + let details; + if (truncation.firstLineExceedsLimit) { + const integral = Number.isInteger(startLine); + const lineBytes = new TextEncoder().encode(integral ? head.split("\n")[0] ?? "" : ""); + const lineSize = integral ? scan.firstLineBytes : 0; + const end = characterEnd(lineBytes, DEFAULT_MAX_BYTES); + outputText = new TextDecoder().decode(lineBytes.subarray(0, end)); + diagnostics.push({ + severity: "warn", + code: "truncated", + message: `Line ${startLineDisplay} is ${formatSize(lineSize)}, exceeds the ${formatSize(DEFAULT_MAX_BYTES)} limit; showing its first ${formatSize(end)}. Use bash: sed -n '${startLineDisplay}p' ${path4} | tail -c +${end + 1}` + }); + details = { truncation: { ...truncation, outputBytes: end, outputLines: 1 } }; + } else if (truncation.truncated) { + const endLineDisplay = startLineDisplay + truncation.outputLines - 1; + const nextOffset = endLineDisplay + 1; + const limitText = truncation.truncatedBy === "lines" ? "" : ` (${formatSize(DEFAULT_MAX_BYTES)} limit)`; + diagnostics.push({ + severity: "info", + code: "truncated", + message: `Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}${limitText}. Use offset=${nextOffset} to continue.` + }); + details = { truncation }; + } else if (userLimitedLines !== void 0 && startLine + userLimitedLines < totalFileLines) { + const remaining = totalFileLines - (startLine + userLimitedLines); + const nextOffset = startLine + userLimitedLines + 1; + diagnostics.push({ + severity: "info", + message: `${remaining} more lines in file. Use offset=${nextOffset} to continue.` + }); + } + return { + output: outputText === "" ? [] : [{ type: "text", text: outputText }], + structuredOutput: outputText, + ...details === void 0 ? {} : { details }, + diagnostics + }; +} + +// node_modules/@earendil-works/pi-durable/dist/tools/write.js +var writeSchema = obj({ + path: str({ description: "Path to the file to write (relative or absolute)" }), + content: str({ description: "Content to write to the file" }) +}, { open: true }); +function createWriteTool() { + return defineTool({ + name: "write", + description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.", + parameters: writeSchema, + async execute(args, api, context) { + const { path: path4, content } = args; + const env = requireEnv(api); + const absolutePath = await resolveToolPath(env, path4, context); + return withFileMutationQueue(env, absolutePath, async () => { + if (context.abortSignal?.aborted) + throw new Error("Operation aborted"); + getOrThrow(await env.writeFile(absolutePath, content, context)); + if (context.abortSignal?.aborted) + throw new Error("Operation aborted"); + return { output: [{ type: "text", text: `Successfully wrote to ${path4}` }] }; + }, context); + } + }); +} + +// node_modules/@earendil-works/pi-durable/dist/tools/index.js +function createCodingTools(options = {}) { + return defineExtension({ + name: "coding-tools", + tools: [createReadTool(options), createWriteTool(), createEditTool(), createBashTool()] + }); +} +var CodingTools = createCodingTools(); + +// events.ts +function defineEvent(name, options = {}) { + const kind = `event.${name}`; + return { name, kind, version: options.version ?? 1, is: (event) => event?.kind === kind }; +} +var NoticeEvent = defineEvent("sausage.notice"); +var EVENT_FEED = "sausage.event-feed"; +var EventLog = defineDoc({ + kind: "sausage.events", + version: 1, + scope: "conversation", + history: "latest", + fork: "initial", + checkpointWhen: () => false, + initial: () => ({ cursors: {} }) +}); +var EventFeed = defineDoc({ + kind: EVENT_FEED, + version: 1, + scope: "conversation", + history: "latest", + fork: "initial", + checkpointWhen: () => false, + initial: () => ({ events: [] }) +}); + +// environment.ts +var CodingTools2 = { ...CodingTools, tools: CodingTools.tools.map((tool) => ({ + ...tool, + execute: (args, api, context) => tool.execute(args, { ...api, env: api.env.forTool(api.callId, tool.name) }, context) +})) }; +var Started = defineDoc({ + kind: "board.started", + version: 1, + checkpointWhen: () => false, + scope: "conversation", + history: "latest", + fork: "initial", + initial: () => ({}) +}); +var ops = Deno.core.ops; + +// extensions.ts +var ops2 = Deno.core.ops; +var encoder2 = new TextEncoder(); +var decoder2 = new TextDecoder(); +var ExtensionState = defineDoc({ kind: "sausage.extensions", version: 1, scope: "session", checkpointWhen: () => false, initial: () => ({ good: null, current: null, error: null }) }); +var Metadata = defineDoc({ kind: "sausage.metadata", version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ label: "", title: "" }), checkpointWhen: () => false }); +async function file(kind, path4, bytes2 = []) { + const result = await ops2.op_file(kind, path4, bytes2); + if (!result.ok) throw Object.assign(new Error(result.error.message), result.error); + return result.value; +} +var fs2 = { + read: async (path4) => decoder2.decode(new Uint8Array(await file("read", path4))), + write: (path4, text) => file("write", path4, Array.from(encoder2.encode(text))), + append: (path4, text) => file("append", path4, Array.from(encoder2.encode(text))), + list: (path4) => file("list", path4), + stat: (path4) => file("stat", path4), + lstat: (path4) => file("lstat", path4), + mkdir: (path4) => file("mkdir", path4), + remove: (path4) => file("remove", path4), + rename: (from, to) => file("rename", from, Array.from(encoder2.encode(to))) +}; + // proxy-models-test.ts -var models = await proxyModels(globalThis.testProxy); +var readProxy = () => Deno.core.ops.op_model_proxy(); +var models = await proxyModels(await readProxy(), readProxy); for (const [provider2, id] of [["openai", "gpt-6.1-sol"], ["anthropic", "claude-opus-5-5"]]) { const model2 = models.getModel(provider2, id); if (model2.cost.input !== 2 || model2.cost.cacheWrite !== 3) throw new Error("catalog prices lost"); @@ -41392,3 +45365,16 @@ for (const [provider2, api] of [["openai", "openai-responses"], ["anthropic", "a const model2 = fallback.getModels(provider2)[0]; if (model2.api !== api || model2.cost.input !== 0) throw new Error("offline transport fallback failed"); } +await fs2.write("/etc/sausage/config.yaml", JSON.stringify({ proxy: { base_url: `${globalThis.testProxy.base_url}/edited`, api_key: "next-key" } })); +var auth = await models.getAuth(models.getModel("openai", "gpt-6.1-sol")); +if (auth.auth.apiKey !== "next-key" || auth.auth.baseUrl !== `${globalThis.testProxy.base_url}/edited/v1`) throw new Error("Proxy edits did not reach the next request"); +await fs2.write("/etc/sausage/config.yaml", JSON.stringify({ proxy: { base_url: "", api_key: "" } })); +var empty = await proxyModels(await readProxy(), readProxy); +var failure = ""; +try { + const result = await empty.completeSimple(empty.getModels("openai")[0], { messages: [{ role: "user", content: "Missing key", timestamp: Date.now() }] }); + failure = result.errorMessage ?? ""; +} catch (error) { + failure = String(error); +} +if (!failure.includes("/etc/sausage/config.yaml")) throw new Error(`Missing proxy settings must name the config file: ${failure}`); diff --git a/host/js/proxy-models-test.ts b/host/js/proxy-models-test.ts index c6cf834..21f8a76 100644 --- a/host/js/proxy-models-test.ts +++ b/host/js/proxy-models-test.ts @@ -1,6 +1,8 @@ /** Exercise both real pi-ai transports and their catalog prices, without provider SDK mocks. */ import { proxyModels } from './proxy-models'; -const models = await proxyModels(globalThis.testProxy); +import { fs } from './extensions'; +const readProxy=()=>Deno.core.ops.op_model_proxy(); +const models = await proxyModels(await readProxy(),readProxy); for (const [provider, id] of [['openai', 'gpt-6.1-sol'], ['anthropic', 'claude-opus-5-5']]) { const model = models.getModel(provider, id); if (model.cost.input !== 2 || model.cost.cacheWrite !== 3) throw new Error('catalog prices lost'); @@ -15,3 +17,14 @@ for (const [provider, api] of [['openai', 'openai-responses'], ['anthropic', 'an const model = fallback.getModels(provider)[0]; if (model.api !== api || model.cost.input !== 0) throw new Error('offline transport fallback failed'); } +await fs.write('/etc/sausage/config.yaml',JSON.stringify({proxy:{base_url:`${globalThis.testProxy.base_url}/edited`,api_key:'next-key'}})); +const auth=await models.getAuth(models.getModel('openai','gpt-6.1-sol')); +if(auth.auth.apiKey!=='next-key'||auth.auth.baseUrl!==`${globalThis.testProxy.base_url}/edited/v1`) throw new Error('Proxy edits did not reach the next request'); +await fs.write('/etc/sausage/config.yaml',JSON.stringify({proxy:{base_url:'',api_key:''}})); +const empty=await proxyModels(await readProxy(),readProxy); +let failure=''; +try { + const result=await empty.completeSimple(empty.getModels('openai')[0],{messages:[{role:'user',content:'Missing key',timestamp:Date.now()}]}); + failure=result.errorMessage??''; +} catch(error) {failure=String(error)} +if(!failure.includes('/etc/sausage/config.yaml')) throw new Error(`Missing proxy settings must name the config file: ${failure}`); diff --git a/host/js/proxy-models.ts b/host/js/proxy-models.ts index b0a2d90..1d3ff9f 100644 --- a/host/js/proxy-models.ts +++ b/host/js/proxy-models.ts @@ -3,15 +3,17 @@ import { createModels } from '@earendil-works/pi-ai/models'; import { openaiProvider } from '@earendil-works/pi-ai/providers/openai'; import { anthropicProvider } from '@earendil-works/pi-ai/providers/anthropic'; -export async function proxyModels(proxy: {base_url: string, api_key: string}) { +export async function proxyModels(proxy: {base_url: string, api_key: string}, readProxy = async () => proxy) { const models = createModels(); const base = proxy.base_url.replace(/\/$/, ''); let catalog: any[] = []; try { - const response = await fetch(`${base}/v1/models`, { - headers: {Authorization: `Bearer ${proxy.api_key}`}, signal: AbortSignal.timeout(5000), - }); - if (response.ok) catalog = (await response.json()).data ?? []; + if (proxy.base_url && proxy.api_key) { + const response = await fetch(`${base}/v1/models`, { + headers: {Authorization: `Bearer ${proxy.api_key}`}, signal: AbortSignal.timeout(5000), + }); + if (response.ok) catalog = (await response.json()).data ?? []; + } } catch { /* An unavailable catalog must not prevent durable recovery. */ } for (const [provider, api, path, fallback] of [ [openaiProvider(), 'openai-responses', '/v1/responses', 'gpt-6.1-sol'], @@ -37,10 +39,13 @@ export async function proxyModels(proxy: {base_url: string, api_key: string}) { }; }); models.setProvider({...provider, baseUrl: entries[0].baseUrl, getModels: () => entries as any, - auth: {apiKey: {name: 'Sausage proxy', resolve: async () => ({ - auth: {apiKey: proxy.api_key, headers: {'Shopify-Usage-Tag': JSON.stringify(['pi', 'sausage'])}}, - source: 'llm-proxy', - })}}, + auth: {apiKey: {name: 'Sausage proxy', resolve: async () => { + const current = await readProxy(); + if (!current.base_url || !current.api_key) throw new Error('Set proxy.base_url and proxy.api_key in /etc/sausage/config.yaml before a model request'); + return {auth:{apiKey:current.api_key, + baseUrl:current.base_url.replace(/\/$/,'') + entries[0].baseUrl.slice(base.length), + headers:{'Shopify-Usage-Tag':JSON.stringify(['pi','sausage'])}},source:'/etc/sausage/config.yaml'}; + }}}, }); } return models; diff --git a/host/js/questions-cases.ts b/host/js/questions-cases.ts index 8598553..1caeb00 100644 --- a/host/js/questions-cases.ts +++ b/host/js/questions-cases.ts @@ -1,5 +1,5 @@ -/** Ultimate server question cases, with a real world fixture. */ +/** Standing agent server question cases, with a real world fixture. */ import { BACKGROUND_CONTEXT as context } from '@earendil-works/chord/context' import {expect,it,describe,afterEach} from './goal-questions-test-support' import {fixture as openFixture} from './goal-questions-fixture' @@ -36,7 +36,7 @@ const decisions = [ describe('questions on a message', () => { it('are stored as the tool validated them, only on reply-expected messages to the user', async () => { const f = await fixture() - const id = await f.ultimate() + const id = await f.standing() const sent = await f.ask(id, { text: 'Decide these.', questions: decisions }) expect(sent.error).toBeUndefined() expect(sent.message).toMatchObject({ state: 'delivered', questions: decisions }) @@ -55,7 +55,7 @@ describe('questions on a message', () => { it('refuses questions the card could not answer, naming the question', async () => { const f = await fixture() - const id = await f.ultimate() + const id = await f.standing() const refused = async (questions: unknown, reason: string) => { const { error } = await f.ask(id, { text: 'Decide.', questions }) expect(error).toContain(reason) @@ -118,7 +118,7 @@ describe('questions on a message', () => { it('answers in the message numbering for every kind, with a note after the answers', async () => { const f = await fixture() - const id = await f.ultimate() + const id = await f.standing() const { message } = await f.ask(id, { text: 'Decide these.', questions: decisions }) expect(userActions).toEqual(['answer', 'dismiss']) await expect( @@ -166,7 +166,7 @@ describe('questions on a message', () => { it('sends a note on its own, and free text for a message without questions', async () => { const f = await fixture() - const id = await f.ultimate() + const id = await f.standing() const { message } = await f.ask(id, { text: 'Decide these.', questions: decisions }) await expect(f.answer({ messageId: message!.id, answers: [], note: ' ' })).rejects.toThrow( 'Invalid answers', @@ -193,9 +193,9 @@ describe('questions on a message', () => { ) }) - it("keeps @ultimate's open message open until its card answers it, naming it by its questions", async () => { + it("keeps @standing's open message open until its card answers it, naming it by its questions", async () => { const f = await fixture() - const id = await f.ultimate() + const id = await f.standing() const { message } = await f.ask(id, { text: 'Decide these.', questions: decisions }) await f.type( f.opened.root.id, @@ -224,7 +224,7 @@ describe('questions on a message', () => { it('dismisses one open question with a one-way note that starts no run, leaving the others open', async () => { const f = await fixture() - const id = await f.ultimate() + const id = await f.standing() const first = (await f.ask(id, { text: 'Keep it running?', questions: [decisions[2]] })) .message! const second = (await f.ask(id, { text: 'Which layout?' })).message! diff --git a/host/js/subagents-test-bundle.js b/host/js/subagents-test-bundle.js index cccd735..e7354b2 100644 --- a/host/js/subagents-test-bundle.js +++ b/host/js/subagents-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text2 = contentText(message.content); if (text2.length > 0) content.push(text2); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base, fragment) { let node = root2; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service, implementation) { const contract = service.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service, object } = candidate; const exposed = memberSchemas(service, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service, input, principal) { - const { name, input: schema } = service.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call2, timestamp) { +function missingResult(call2, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call2.id, @@ -20108,7 +20108,7 @@ function missingResult(call2, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text2} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call2, tool, result, truncatio } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call2, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call2, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call2.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28631,6 +28631,6646 @@ var MemoryStorage = class { } }; +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root2) { + const anchors = /* @__PURE__ */ new Set(); + visit(root2, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text2, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text2; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text2.length <= endStep) + return text2; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text2, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text2[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text2[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text2, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text2[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text2[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text2; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text2; + if (onFold) + onFold(); + let res = text2.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text2.length; + if (fold === 0) + res = ` +${indent}${text2.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text2[fold]}\\`; + res += ` +${indent}${text2.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text2, i, indent) { + let end = i; + let start2 = i + 1; + let ch = text2[start2]; + while (ch === " " || ch === " ") { + if (i < start2 + indent) { + ch = text2[++i]; + } else { + do { + ch = text2[++i]; + } while (ch && ch !== "\n"); + end = i; + start2 = i + 1; + ch = text2[start2]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start2 = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start2 > limit) + return true; + start2 = i + 1; + if (strLen - start2 <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start2 = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start2, i) + "\\ "; + i += 1; + start2 = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start2, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start2 = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start2, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start2 = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start2 ? str2 + json.slice(start2) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start2 = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start2) { + value2 = value2.substring(start2.length); + start2 = start2.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start2}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start2}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start: start2, end } = flowChars; + if (lines2.length === 0) { + return start2 + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start2; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start2}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start2 = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start2 ?? (start2 = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start2 ?? (start2 = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start2 ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start: start2, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start2, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start2[start2.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start2, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start: start2, value: value2 } of bs.items) { + const props = resolveProps(start2, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start2, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start: start2, key, sep, value: value2 } = collItem; + const props = resolveProps(start2, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start2) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start2, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start2 = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start2, start2, start2] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start2 + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start2, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start2 + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start2, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start: start2, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start2, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start2, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start: start2, key, sep, value: value2 }) { + let res = ""; + for (const st of start2) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start2 = this.lineStarts[low - 1]; + return { line: low, col: offset - start2 + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start2 = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start: start2, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start2 = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start2 = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start2.push(this.sourceToken); + map3.items.push({ start: start2 }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start2.push(this.sourceToken); + map3.items.push({ start: start2, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start3 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start3, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start3 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start3, key, sep }] + }); + } else if (start2.length > 0) { + it.sep = it.sep.concat(start2, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start: start2, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start: start2, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start: start2 }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start2 = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start: start2, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start2 = getFirstKeyStartProps(prev); + start2.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start2 = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start2, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start2.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -29067,7 +35707,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -29192,7 +35832,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text2) { +function splitLines2(text2) { const hasTrailingNl = text2.endsWith("\n"); const result = text2.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -30103,8 +36743,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -30306,11 +36946,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -30527,7 +37167,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -30756,7 +37396,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -30858,8 +37503,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -30965,8 +37610,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -31057,20 +37702,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -31106,9 +37751,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -31116,8 +37761,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -31135,10 +37780,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -31574,7 +38219,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -31582,7 +38227,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -31627,21 +38272,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -31651,12 +38296,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -31741,7 +38386,7 @@ var held2 = defineExtension({ name: "hold", tools: [defineTool({ name: "hold", d } })] }); if (globalThis.subagentsMode === "kill") { const install = registry.install.bind(registry); - registry.install = (extension) => install(extension.name !== "subagents" ? extension : { ...extension, tasks: extension.tasks.map((task) => task.definition.name !== "ultimate.subagent-reporter" ? task : { definition: { ...task.definition, phases: { ...task.definition.phases, report: async (_task, _runtime, ctx) => { + registry.install = (extension) => install(extension.name !== "subagents" ? extension : { ...extension, tasks: extension.tasks.map((task) => task.definition.name !== "standing.subagent-reporter" ? task : { definition: { ...task.definition, phases: { ...task.definition.phases, report: async (_task, _runtime, ctx) => { await fs.write("/report-ready", "yes"); await awaitWithContext(new Promise(() => { }), ctx); @@ -31795,17 +38440,19 @@ try { assert(await service.standing("scout", BACKGROUND_CONTEXT) === standing, "Standing refresh must reuse its conversation"); const standingRecord = await harness.commit((tx) => tx.conversation(standing), BACKGROUND_CONTEXT); assert(!standingRecord.owner, "Standing must be ownerless"); - const scoutFile = await fs.read("/src/sausage/agents/scout.md"); - await fs.write("/src/sausage/agents/scout.md", scoutFile.replace("Scout instructions", "Updated instructions")); + const config = parse(await fs.read("/etc/sausage/config.yaml")); + const save = () => fs.write("/etc/sausage/config.yaml", JSON.stringify(config)); + config.roster[0].prompt = "Updated instructions"; + await save(); await service.standing("scout", BACKGROUND_CONTEXT); - assert((await (await harness.conversation(standing, BACKGROUND_CONTEXT)).agent(BACKGROUND_CONTEXT)).instructions === "Updated instructions", "Standing refresh must reread instructions"); + assert((await (await harness.conversation(standing, BACKGROUND_CONTEXT)).agent(BACKGROUND_CONTEXT)).instructions.includes("Updated instructions"), "Standing refresh must reread instructions"); const answer2 = await call({ action: "start", agent: "scout", task: "facts" }); assert(text(answer2) === "Returned model: faux/faux-1\nChild: facts", `Foreground answer: ${JSON.stringify(answer2)}`); const [first] = await children(); assert(JSON.stringify(await chain(first.conversationId)) === JSON.stringify([String(first.conversationId), String(root.id)]), "Anchor ownership chain"); const record2 = await harness.commit((tx) => tx.conversation(first.conversationId), BACKGROUND_CONTEXT); const anchor = await harness.getTask(record2.owner.taskId, BACKGROUND_CONTEXT); - assert(anchor?.kind === "ultimate.subagent-anchor", "Child owner must be anchor"); + assert(anchor?.kind === "standing.subagent-anchor", "Child owner must be anchor"); const child = await harness.conversation(first.conversationId, BACKGROUND_CONTEXT); assert(!(await child.agent(BACKGROUND_CONTEXT)).tools.some((tool) => tool.name === "subagent"), "Tool denials"); assert((await root.agent(BACKGROUND_CONTEXT)).tools.some((tool) => tool.name === "subagent"), "Parent tools remain unchanged"); @@ -31851,28 +38498,40 @@ try { assert(!(await harness.snapshot(LiveDoc, third.conversationId, BACKGROUND_CONTEXT))?.run, "Stop must end child"); assert((await reports()).length === 2, "Stop must suppress aborted report"); assert(text(await call({ action: "start", agent: "scout", task: "no", isolate: "worktree" })).includes("requires the workspaces extension"), "Worktree seam"); - await fs.write("/src/sausage/agents/worker.md", "---\nname: worker\ndescription: Worker\nfamily: fast\ntools: []\n---\nWorker body"); - await fs.mkdir("/src/sausage/.sausage"); - await fs.mkdir("/src/sausage/.sausage/agents"); - await fs.write("/src/sausage/.sausage/agents/worker.md", "---\nname: worker\naddTools: [hold]\n---\nOverlay body"); - await fs.write("/src/sausage/agents/models.json", JSON.stringify({ default: { model: "faux/faux-1" }, fast: { model: "faux/faux-1", thinking: "low" } })); + config.roster.push({ name: "worker", description: "Worker", model: "faux/faux-1", thinking: "low", tools: [], addTools: ["hold"], prompt: "Worker body" }); + await save(); await call({ action: "start", agent: "worker", task: "family one" }); const familyChild = (await children()).at(-1); const firstAgent = await (await harness.conversation(familyChild.conversationId, BACKGROUND_CONTEXT)).agent(BACKGROUND_CONTEXT); - assert(firstAgent.model?.modelId === "faux-1" && firstAgent.thinkingLevel === "low", "Worker must resolve fast family"); - assert(firstAgent.tools.map((tool) => tool.name).join(",") === "hold", "Project overlay must add a tool"); - assert(firstAgent.instructions.includes("Worker body") && firstAgent.instructions.includes("Overlay body"), "Child must use overlaid instructions"); + assert(firstAgent.model?.modelId === "faux-1" && firstAgent.thinkingLevel === "low", "Worker must resolve roster model and thinking"); + assert(firstAgent.tools.map((tool) => tool.name).join(",") === "hold", "Roster addTools must add a tool"); + assert(firstAgent.instructions.includes("Worker body"), "Child must use roster instructions"); const provider2 = models.getProvider("faux"), template = models.getModels("faux")[0]; models.setProvider({ ...provider2, getModels: () => [template, { ...template, id: "second" }] }); - await fs.write("/src/sausage/agents/models.json", JSON.stringify({ default: { model: "faux/faux-1" }, fast: { model: "faux/second", thinking: "high" } })); + Object.assign(config.roster[1], { model: "faux/second", thinking: "high" }); + await save(); await call({ action: "start", agent: "worker", task: "family two" }); const secondFamilyChild = (await children()).at(-1); const secondAgent = await (await harness.conversation(secondFamilyChild.conversationId, BACKGROUND_CONTEXT)).agent(BACKGROUND_CONTEXT); - assert(secondAgent.model?.modelId === "second" && secondAgent.thinkingLevel === "high", "Next child must use edited family without restart"); + assert(secondAgent.model?.modelId === "second" && secondAgent.thinkingLevel === "high", "Next child must use edited roster without restart"); globalThis.childPin = { provider: "faux", modelId: "faux-1" }; await call({ action: "start", agent: "worker", task: "pin" }); const pinnedChild = (await children()).at(-1); assert((await (await harness.conversation(pinnedChild.conversationId, BACKGROUND_CONTEXT)).agent(BACKGROUND_CONTEXT)).model?.modelId === "faux-1", "models.pin must apply to subagents"); + globalThis.childPin = void 0; + config.standing = "renamed-scout"; + Object.assign(config.roster[0], { name: config.standing, model: "faux/second" }); + await save(); + assert(await service.standing(config.standing, BACKGROUND_CONTEXT) === standing, "Rename must retain the standing conversation"); + faux.setResponses([(transcript) => { + const prompt = JSON.stringify(transcript.messages.filter((m) => m.role === "system")); + assert(prompt.includes("You are @renamed-scout."), "Renamed standing prompt must use the configured name"); + return fauxAssistantMessage("I am @renamed-scout."); + }]); + const primary = await harness.conversation(standing, BACKGROUND_CONTEXT); + await (await primary.submit({ type: "input", content: "Who are you?" }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); + assert((await primary.agent(BACKGROUND_CONTEXT)).model?.modelId === "second", "Standing model edit applies at its next run"); + assert(JSON.stringify((await primary.context(BACKGROUND_CONTEXT)).entries).includes("I am @renamed-scout."), "Same conversation answers with the new name"); } } finally { gate.resolve(); diff --git a/host/js/subagents-test.ts b/host/js/subagents-test.ts index 7cff4c2..dea002f 100644 --- a/host/js/subagents-test.ts +++ b/host/js/subagents-test.ts @@ -5,6 +5,7 @@ import { fauxProvider, fauxAssistantMessage, fauxToolCall } from '@earendil-work import { Harness, createRegistry, defineExtension, defineTool, LiveDoc, InboxDoc } from '@earendil-works/pi-durable'; import { obj } from '@earendil-works/pi-schema'; import { loadExtensions, fs } from './extensions'; +import { parse } from 'yaml'; import { conversationChains } from './environment'; import { openStorage } from './sqlite'; const assert = (value:any,message:string)=>{if(!value)throw new Error(message);}; @@ -17,7 +18,7 @@ const gate=Promise.withResolvers(), parentGate=Promise.withResolvers const held=defineExtension({name:'hold',tools:[defineTool({name:'hold',description:'Wait for test gate',parameters:obj({}),replay:'safe',execute:async(_args,api,ctx)=>{holding.add(api.conversationId);await awaitWithContext(api.conversationId===root.id?parentGate.promise:gate.promise,ctx);return {output:[{type:'text',text:'released'}]};}})]}); if(globalThis.subagentsMode==='kill') { const install=registry.install.bind(registry); - registry.install=(extension:any)=>install(extension.name!=='subagents'?extension:{...extension,tasks:extension.tasks.map((task:any)=>task.definition.name!=='ultimate.subagent-reporter'?task:{definition:{...task.definition,phases:{...task.definition.phases,report:async(_task:any,_runtime:any,ctx:any)=>{await fs.write('/report-ready','yes');await awaitWithContext(new Promise(()=>{}),ctx);}}}})}); + registry.install=(extension:any)=>install(extension.name!=='subagents'?extension:{...extension,tasks:extension.tasks.map((task:any)=>task.definition.name!=='standing.subagent-reporter'?task:{definition:{...task.definition,phases:{...task.definition.phases,report:async(_task:any,_runtime:any,ctx:any)=>{await fs.write('/report-ready','yes');await awaitWithContext(new Promise(()=>{}),ctx);}}}})}); } const route=(transcript:any):any=>{ faux.appendResponses([route]); @@ -57,17 +58,18 @@ try { assert(await service.standing('scout',context)===standing,'Standing refresh must reuse its conversation'); const standingRecord=await harness.commit((tx:any)=>tx.conversation(standing),context); assert(!standingRecord.owner,'Standing must be ownerless'); - const scoutFile=await fs.read('/src/sausage/agents/scout.md'); - await fs.write('/src/sausage/agents/scout.md',scoutFile.replace('Scout instructions','Updated instructions')); + const config=parse(await fs.read('/etc/sausage/config.yaml')); + const save=()=>fs.write('/etc/sausage/config.yaml',JSON.stringify(config)); + config.roster[0].prompt='Updated instructions';await save(); await service.standing('scout',context); - assert((await (await harness.conversation(standing,context))!.agent(context)).instructions==='Updated instructions','Standing refresh must reread instructions'); + assert((await (await harness.conversation(standing,context))!.agent(context)).instructions.includes('Updated instructions'),'Standing refresh must reread instructions'); const answer=await call({action:'start',agent:'scout',task:'facts'}); assert(text(answer)==='Returned model: faux/faux-1\nChild: facts',`Foreground answer: ${JSON.stringify(answer)}`); const [first]=await children(); assert(JSON.stringify(await chain(first.conversationId))===JSON.stringify([String(first.conversationId),String(root.id)]),'Anchor ownership chain'); const record=await harness.commit((tx:any)=>tx.conversation(first.conversationId),context); const anchor=await harness.getTask(record!.owner!.taskId,context); - assert(anchor?.kind==='ultimate.subagent-anchor','Child owner must be anchor'); + assert(anchor?.kind==='standing.subagent-anchor','Child owner must be anchor'); const child=(await harness.conversation(first.conversationId,context))!; assert(!(await child.agent(context)).tools.some((tool:any)=>tool.name==='subagent'),'Tool denials'); assert((await root.agent(context)).tools.some((tool:any)=>tool.name==='subagent'),'Parent tools remain unchanged'); @@ -106,26 +108,36 @@ try { assert(!(await harness.snapshot(LiveDoc,third.conversationId,context))?.run,'Stop must end child'); assert((await reports()).length===2,'Stop must suppress aborted report'); assert(text(await call({action:'start',agent:'scout',task:'no',isolate:'worktree'})).includes('requires the workspaces extension'),'Worktree seam'); - await fs.write('/src/sausage/agents/worker.md','---\nname: worker\ndescription: Worker\nfamily: fast\ntools: []\n---\nWorker body'); - await fs.mkdir('/src/sausage/.sausage');await fs.mkdir('/src/sausage/.sausage/agents'); - await fs.write('/src/sausage/.sausage/agents/worker.md','---\nname: worker\naddTools: [hold]\n---\nOverlay body'); - await fs.write('/src/sausage/agents/models.json',JSON.stringify({default:{model:'faux/faux-1'},fast:{model:'faux/faux-1',thinking:'low'}})); + config.roster.push({name:'worker',description:'Worker',model:'faux/faux-1',thinking:'low',tools:[],addTools:['hold'],prompt:'Worker body'});await save(); await call({action:'start',agent:'worker',task:'family one'}); const familyChild=(await children()).at(-1)!; const firstAgent=await (await harness.conversation(familyChild.conversationId,context))!.agent(context); - assert(firstAgent.model?.modelId==='faux-1'&&firstAgent.thinkingLevel==='low','Worker must resolve fast family'); - assert(firstAgent.tools.map((tool:any)=>tool.name).join(',')==='hold','Project overlay must add a tool'); - assert(firstAgent.instructions.includes('Worker body')&&firstAgent.instructions.includes('Overlay body'),'Child must use overlaid instructions'); + assert(firstAgent.model?.modelId==='faux-1'&&firstAgent.thinkingLevel==='low','Worker must resolve roster model and thinking'); + assert(firstAgent.tools.map((tool:any)=>tool.name).join(',')==='hold','Roster addTools must add a tool'); + assert(firstAgent.instructions.includes('Worker body'),'Child must use roster instructions'); const provider=models.getProvider('faux')!, template=models.getModels('faux')[0]; models.setProvider({...provider,getModels:()=>[template,{...template,id:'second'}]}); - await fs.write('/src/sausage/agents/models.json',JSON.stringify({default:{model:'faux/faux-1'},fast:{model:'faux/second',thinking:'high'}})); + Object.assign(config.roster[1],{model:'faux/second',thinking:'high'});await save(); await call({action:'start',agent:'worker',task:'family two'}); const secondFamilyChild=(await children()).at(-1)!; const secondAgent=await (await harness.conversation(secondFamilyChild.conversationId,context))!.agent(context); - assert(secondAgent.model?.modelId==='second'&&secondAgent.thinkingLevel==='high','Next child must use edited family without restart'); + assert(secondAgent.model?.modelId==='second'&&secondAgent.thinkingLevel==='high','Next child must use edited roster without restart'); globalThis.childPin={provider:'faux',modelId:'faux-1'}; await call({action:'start',agent:'worker',task:'pin'}); const pinnedChild=(await children()).at(-1)!; assert((await (await harness.conversation(pinnedChild.conversationId,context))!.agent(context)).model?.modelId==='faux-1','models.pin must apply to subagents'); + globalThis.childPin=undefined; + config.standing='renamed-scout'; + Object.assign(config.roster[0],{name:config.standing,model:'faux/second'});await save(); + assert(await service.standing(config.standing,context)===standing,'Rename must retain the standing conversation'); + faux.setResponses([(transcript:any)=>{ + const prompt=JSON.stringify(transcript.messages.filter((m:any)=>m.role==='system')); + assert(prompt.includes('You are @renamed-scout.'),'Renamed standing prompt must use the configured name'); + return fauxAssistantMessage('I am @renamed-scout.'); + }]); + const primary=(await harness.conversation(standing,context))!; + await (await primary.submit({type:'input',content:'Who are you?'},context)).wait(context); + assert((await primary.agent(context)).model?.modelId==='second','Standing model edit applies at its next run'); + assert(JSON.stringify((await primary.context(context)).entries).includes('I am @renamed-scout.'),'Same conversation answers with the new name'); } } finally {gate.resolve();parentGate.resolve();await loader.close();await harness.close(context);} diff --git a/host/js/undo-harness-test-bundle.js b/host/js/undo-harness-test-bundle.js index cc1d300..0152a38 100644 --- a/host/js/undo-harness-test-bundle.js +++ b/host/js/undo-harness-test-bundle.js @@ -259,16 +259,16 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js function createTypedMetrics(metrics, schemas) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -314,8 +314,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -523,7 +523,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -540,7 +540,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -2869,12 +2869,12 @@ function arr(items, options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -2942,8 +2942,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3019,10 +3019,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3032,12 +3032,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base, fragment) { let node = root2; @@ -3124,9 +3124,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3188,26 +3188,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3222,7 +3222,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3231,10 +3231,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3340,8 +3340,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -3354,7 +3354,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3364,11 +3364,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -3382,19 +3382,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3406,9 +3406,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -3422,12 +3422,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3435,7 +3435,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3443,31 +3443,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -3563,11 +3563,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -3960,9 +3960,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4221,9 +4221,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4289,9 +4289,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4302,7 +4302,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -4711,9 +4711,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5065,9 +5065,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check) : new Validator(schema, options, check); +function compile(schema4, options = NO_OPTIONS) { + const check = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check) : new Validator(schema4, options, check); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5076,9 +5076,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check) { + constructor(schema4, options, check) { this.check = check; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5110,18 +5110,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -8590,19 +8590,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -9361,14 +9361,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record = { ...record, retiredAt: seq }; + record = { ...record, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -9816,8 +9816,8 @@ var Writer = class { } if (stored.length > 0) { try { - result2 = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result2 = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -9850,8 +9850,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result2?.stored && "refused" in result2 ? result2.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -9869,7 +9869,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -10729,7 +10729,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -10739,15 +10739,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -10758,7 +10758,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -10771,7 +10771,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -10840,7 +10840,7 @@ var SessionImpl = class { const conversationId = record.scope.kind === "conversation" ? record.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -10848,7 +10848,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -10903,7 +10903,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -10931,9 +10931,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -11564,7 +11564,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -11572,27 +11572,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -12141,7 +12141,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -12149,7 +12149,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -12564,21 +12564,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -12620,14 +12620,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -12654,9 +12654,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence >> 37n & 0x0fn); bytes2[7] = Number(sequence >> 29n & 0xffn); @@ -12835,12 +12835,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -12854,16 +12854,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -15448,20 +15448,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record) => [record.id, record.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record, name) { const memos = record?.memos; @@ -16369,13 +16369,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -16970,18 +16970,18 @@ async function afterHarnessResult(runtime, input, call, tool, result2, truncatio } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result2) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result2.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result2.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -17161,7 +17161,7 @@ function errorTextOf(result2, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result2, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result2.diagnostics ?? []]; const content = [...result2.output ?? []]; if (diagnostics.length > 0) @@ -17175,7 +17175,7 @@ async function appendToolResult(tx, conversationId, call, result2, meta) { ...result2.usage === void 0 ? {} : { usage: result2.usage }, isError: result2.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result2.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result2.usage); @@ -21481,8 +21481,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -21588,8 +21588,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -21680,20 +21680,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -21729,9 +21729,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -21739,8 +21739,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -21758,10 +21758,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -22197,7 +22197,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -22205,7 +22205,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -22250,21 +22250,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record; if (action.create !== void 0) { record = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record = parseJson(row.record); @@ -22274,12 +22274,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record = { ...record, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record), id); + record = { ...record, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record), id); } if (isCurrentOnly(record)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -22334,6 +22334,2273 @@ async function openStorage(path2) { return SqliteStorage.open(database); } +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path2) { + const ctrl = callVisitor(key, node, visitor, path2); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path2, ctrl); + return visit_(key, ctrl, visitor, path2); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path2 = Object.freeze(path2.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path2); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path2 = Object.freeze(path2.concat(node)); + const ck = visit_("key", node.key, visitor, path2); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path2); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path2) { + const ctrl = await callVisitor(key, node, visitor, path2); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path2, ctrl); + return visitAsync_(key, ctrl, visitor, path2); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path2 = Object.freeze(path2.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path2); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path2 = Object.freeze(path2.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path2); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path2); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path2) { + if (typeof visitor === "function") + return visitor(key, node, path2); + if (isMap(node)) + return visitor.Map?.(key, node, path2); + if (isSeq(node)) + return visitor.Seq?.(key, node, path2); + if (isPair(node)) + return visitor.Pair?.(key, node, path2); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path2); + if (isAlias(node)) + return visitor.Alias?.(key, node, path2); + return void 0; +} +function replaceNode(key, path2, node) { + const parent = path2[path2.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path2, value2) { + let v = value2; + for (let i = path2.length - 1; i >= 0; --i) { + const k = path2[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path2) => path2 == null || typeof path2 === "object" && !!path2[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path2, value2) { + if (isEmptyPath(path2)) + this.add(value2); + else { + const [key, ...rest] = path2; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path2) { + const [key, ...rest] = path2; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path2, keepScalar) { + const [key, ...rest] = path2; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path2) { + const [key, ...rest] = path2; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path2, value2) { + const [key, ...rest] = path2; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path2) => { + let item = cst; + for (const [field, index] of path2) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path2) => { + const parent = visit2.itemAtPath(cst, path2.slice(0, -1)); + const field = path2[path2.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path2, item, visitor) { + let ctrl = visitor(item, path2); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path2.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path2); + } + } + return typeof ctrl === "function" ? ctrl(item, path2) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); + // events.ts function defineEvent(name, options = {}) { const kind = `event.${name}`; diff --git a/host/js/watchdog-test-bundle.js b/host/js/watchdog-test-bundle.js index 3cab240..76e7181 100644 --- a/host/js/watchdog-test-bundle.js +++ b/host/js/watchdog-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base2, fragment) { let node = root2; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base2) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base2) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base2); + const b = this.baseOf(schema4, base2); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base2, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base2, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base2, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base2, next); + next = this.convert(schema4, base2, next); } if (!matched && additional !== void 0) next = this.convert(additional, base2, next); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base2) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base2) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base2); + const b = this.baseOf(schema4, base2); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base2) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base2) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base2) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base2)); + set2(key, this.coerceTypes(value2[key], property, base2)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base2)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base2)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base2)); + set2(key, this.coerceTypes(value2[key], additional, base2)); } return out ?? value2; } - coerceItems(value2, schema, base2) { + coerceItems(value2, schema4, base2) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base2) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base2, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service2, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service2.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service2, implementation) { const contract = service2.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host.dev, report: (error) => host.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service: service2, object } = candidate; const exposed = memberSchemas(service2, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service2, input, principal) { - const { name, input: schema } = service2.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service2.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service2)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call, timestamp) { +function missingResult(call, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call.id, @@ -20108,7 +20108,7 @@ function missingResult(call, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks: tasks2, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call, tool, result, truncation } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28631,6 +28631,6646 @@ var MemoryStorage = class { } }; +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root2) { + const anchors = /* @__PURE__ */ new Set(); + visit(root2, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -29067,7 +35707,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -29192,7 +35832,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -30103,8 +36743,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -30306,11 +36946,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -30527,7 +37167,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -30756,7 +37396,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -30858,8 +37503,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -30965,8 +37610,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -31057,20 +37702,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -31106,9 +37751,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -31116,8 +37761,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -31135,10 +37780,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -31574,7 +38219,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -31582,7 +38227,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -31627,21 +38272,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -31651,12 +38296,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); @@ -31762,11 +38407,11 @@ var create = async (title) => harness.commit(async (tx) => { Object.assign(await tx.doc(Metadata, record2.id), { title }); return record2.id; }, BACKGROUND_CONTEXT); -var primary = (await harness.snapshot(Standing, root.id, BACKGROUND_CONTEXT)).ultimate; +var primary = (await harness.snapshot(Standing, root.id, BACKGROUND_CONTEXT))["$standing"]; if (!primary) { - primary = await create("@ultimate"); + primary = await create("@standing"); await harness.commit(async (tx) => { - (await tx.doc(Standing, root.id)).ultimate = primary; + (await tx.doc(Standing, root.id))["$standing"] = primary; }, BACKGROUND_CONTEXT); } var submit = async (id, text, requestId) => (await (await harness.conversation(id, BACKGROUND_CONTEXT)).submit({ type: "input", content: text, requestId }, BACKGROUND_CONTEXT)).wait(BACKGROUND_CONTEXT); @@ -31811,7 +38456,7 @@ try { await until2(async () => (await reports(branch)).length === 1); await harness.waitForIdle(BACKGROUND_CONTEXT); assert((await retries(branch)).length === 1, "Expected one retry"); - assert((await reports(branch))[0].to === primary, "The message must reach @ultimate"); + assert((await reports(branch))[0].to === primary, "The message must reach @standing"); assert((await reports(branch))[0].text.includes("After one automatic retry"), "Report must describe its retry"); await until2(async () => (await service.failures(0)).length === 1); const history = await service.failures(0); diff --git a/host/js/watchdog-test.ts b/host/js/watchdog-test.ts index 2c4aac8..a701ece 100644 --- a/host/js/watchdog-test.ts +++ b/host/js/watchdog-test.ts @@ -38,8 +38,8 @@ const create = async (title: string) => harness.commit(async (tx: any) => { Object.assign(await tx.doc(Metadata, record.id), {title}); return record.id; }, context); -let primary = (await harness.snapshot(Standing, root.id, context)).ultimate; -if (!primary) {primary = await create('@ultimate'); await harness.commit(async (tx: any) => {(await tx.doc(Standing, root.id)).ultimate = primary}, context)} +let primary = (await harness.snapshot(Standing, root.id, context))['$standing']; +if (!primary) {primary = await create('@standing'); await harness.commit(async (tx: any) => {(await tx.doc(Standing, root.id))['$standing'] = primary}, context)} const submit = async (id: number, text: string, requestId?: string) => (await (await harness.conversation(id, context))!.submit({type: 'input', content: text, requestId}, context)).wait(context); const requests = async (id: number) => (await storage.scanSubmissions({conversationId: id}, 100, undefined, context)).items; const retries = async (id: number) => (await requests(id)).filter((r: any) => r.requestId?.startsWith('watchdog-retry:')); @@ -70,7 +70,7 @@ try { await until(async () => (await reports(branch)).length === 1); await harness.waitForIdle(context); assert((await retries(branch)).length === 1, 'Expected one retry'); - assert((await reports(branch))[0].to === primary, 'The message must reach @ultimate'); + assert((await reports(branch))[0].to === primary, 'The message must reach @standing'); assert((await reports(branch))[0].text.includes('After one automatic retry'), 'Report must describe its retry'); await until(async () => (await service.failures(0)).length === 1); const history = await service.failures(0); diff --git a/host/js/workspaces-test-bundle.js b/host/js/workspaces-test-bundle.js index c0e9198..e9f7607 100644 --- a/host/js/workspaces-test-bundle.js +++ b/host/js/workspaces-test-bundle.js @@ -263,8 +263,8 @@ var require_dist = __commonJS({ }; return parseAny(); }; - var parse = parseJSON; - exports.parse = parse; + var parse2 = parseJSON; + exports.parse = parse2; } }); @@ -284,10 +284,10 @@ __export(context_exports, { }); // node_modules/@earendil-works/pi-telemetry/dist/metrics.js -function createTypedMetrics(metrics, schemas) { +function createTypedMetrics(metrics, schemas2) { const definitions = /* @__PURE__ */ new Map(); - for (const schema of schemas) { - for (const [name, definition] of Object.entries(schema.metrics ?? {})) + for (const schema4 of schemas2) { + for (const [name, definition] of Object.entries(schema4.metrics ?? {})) definitions.set(name, definition); } return { @@ -333,8 +333,8 @@ Object.freeze(noopTelemetrySpan); var NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan; // node_modules/@earendil-works/pi-telemetry/dist/index.js -function defineTelemetrySchema(schema) { - return schema; +function defineTelemetrySchema(schema4) { + return schema4; } function bindTypedSpanStarter(telemetryContext) { const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span))); @@ -571,7 +571,7 @@ function createAssistantMessageEventStream() { } // node_modules/@earendil-works/pi-ai/dist/api/lazy.js -function createSetupErrorMessage(model2, error, timestamp) { +function createSetupErrorMessage(model2, error, timestamp2) { return { role: "assistant", content: [], @@ -588,7 +588,7 @@ function createSetupErrorMessage(model2, error, timestamp) { }, stopReason: "error", errorMessage: error instanceof Error ? error.message : String(error), - timestamp + timestamp: timestamp2 }; } function hasResult(source) { @@ -1385,11 +1385,11 @@ function getCurrentTools(messages) { function getCurrentSystemMessage(messages) { const content = []; const sections = /* @__PURE__ */ new Map(); - let timestamp; + let timestamp2; for (const message of messages) { if (!isSystemMessage(message)) continue; - timestamp ??= message.timestamp; + timestamp2 ??= message.timestamp; const text = contentText(message.content); if (text.length > 0) content.push(text); @@ -1401,14 +1401,14 @@ function getCurrentSystemMessage(messages) { } } const tools = getCurrentTools(messages); - if (timestamp === void 0 && tools.length === 0) + if (timestamp2 === void 0 && tools.length === 0) return void 0; return { role: "system", content: content.join("\n\n"), ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}, ...tools.length > 0 ? { toolsAdded: tools } : {}, - timestamp: timestamp ?? 0 + timestamp: timestamp2 ?? 0 }; } function getCurrentSystemPrompt(messages) { @@ -3332,11 +3332,11 @@ function lit(value2, options = {}) { function oneOf(values, options = {}) { return { enum: values, ...options }; } -function union(schemas, options = {}) { - return { anyOf: schemas, ...options }; +function union(schemas2, options = {}) { + return { anyOf: schemas2, ...options }; } -function nullable(schema, options = {}) { - return { anyOf: [schema, { type: "null" }], ...options }; +function nullable(schema4, options = {}) { + return { anyOf: [schema4, { type: "null" }], ...options }; } function arr(items, options = {}) { return { type: "array", items, ...options }; @@ -3352,12 +3352,12 @@ function bytes(options = {}) { } var Optional = class { schema; - constructor(schema) { - this.schema = schema; + constructor(schema4) { + this.schema = schema4; } }; -function opt(schema) { - return new Optional(schema); +function opt(schema4) { + return new Optional(schema4); } function obj(properties, options = {}) { const { open, ...annotations } = options; @@ -3425,8 +3425,8 @@ var Resolver = class { if (this.indexed) return; this.indexed = true; - for (const [uri, schema] of Object.entries(this.options.schemas ?? {})) { - this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema); + for (const [uri, schema4] of Object.entries(this.options.schemas ?? {})) { + this.registry.set(documentOf(resolveUri(uri, DEFAULT_BASE)), schema4); } this.resources.set(DEFAULT_BASE, this.root); this.index(this.root, DEFAULT_BASE); @@ -3502,10 +3502,10 @@ var Resolver = class { for (const key of SCHEMA_KEYWORDS) this.index(node[key], b); for (const key of MAP_KEYWORDS) { - const map2 = node[key]; - if (isSchemaObject(map2)) - for (const k of Object.keys(map2)) - this.index(map2[k], b); + const map3 = node[key]; + if (isSchemaObject(map3)) + for (const k of Object.keys(map3)) + this.index(map3[k], b); } for (const key of ARRAY_KEYWORDS) { const list = node[key]; @@ -3515,12 +3515,12 @@ var Resolver = class { } } load(doc) { - const schema = this.registry.get(doc); - if (schema === void 0) + const schema4 = this.registry.get(doc); + if (schema4 === void 0) return void 0; - this.resources.set(doc, schema); - this.index(schema, doc); - return schema; + this.resources.set(doc, schema4); + this.index(schema4, doc); + return schema4; } pointer(root2, base, fragment) { let node = root2; @@ -3607,9 +3607,9 @@ var Coercer = class { * convert the same children (and all fail) would convert them once per branch, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; } /** `value` coerced: a copy along the changed paths only, or `value` itself when nothing changes. */ coerce(value2) { @@ -3671,26 +3671,26 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 1: optional nulls // --------------------------------------------------------------------------------------------------------------- - dropOptionalNulls(value2, schema, base) { - if (!isSchemaObject(schema)) + dropOptionalNulls(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); if (Array.isArray(value2)) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return itemSchema === void 0 ? item : this.dropOptionalNulls(item, itemSchema, b); }); } if (!isPlainObject(value2)) return value2; - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; - if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema.properties)) + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; + if (patterns.length === 0 && additional === void 0 && !isSchemaObject(schema4.properties)) return value2; - const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const required = new Set(Array.isArray(schema4.required) ? schema4.required : []); let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3705,7 +3705,7 @@ var Coercer = class { delete out[key]; continue; } - set(key, this.dropOptionalNulls(value2[key], property, b)); + set2(key, this.dropOptionalNulls(value2[key], property, b)); } if (patterns.length > 0 || additional !== void 0) { for (const key of Object.keys(value2)) { @@ -3714,10 +3714,10 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); + set2(key, this.dropOptionalNulls((out ?? value2)[key], item, b)); } if (!matched && additional !== void 0) - set(key, this.dropOptionalNulls(value2[key], additional, b)); + set2(key, this.dropOptionalNulls(value2[key], additional, b)); } } return out ?? value2; @@ -3823,8 +3823,8 @@ var Coercer = class { return value2; const rest = Array.isArray(node.items) ? void 0 : node.items; return mapItems(value2, (item2, i) => { - const schema = i < prefix.length ? prefix[i] : rest; - return schema === void 0 ? item2 : this.convert(schema, base, item2); + const schema4 = i < prefix.length ? prefix[i] : rest; + return schema4 === void 0 ? item2 : this.convert(schema4, base, item2); }); } if (Array.isArray(value2)) { @@ -3837,7 +3837,7 @@ var Coercer = class { if (!isPlainObject(value2)) return value2; const properties = isSchemaObject(node.properties) ? node.properties : {}; - const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema]) => [sharedRegex(pattern), schema]) : []; + const patterns = isSchemaObject(node.patternProperties) ? Object.entries(node.patternProperties).map(([pattern, schema4]) => [sharedRegex(pattern), schema4]) : []; const additional = isSchemaObject(node.additionalProperties) ? node.additionalProperties : void 0; let out; for (const key of Object.keys(value2)) { @@ -3847,11 +3847,11 @@ var Coercer = class { let matched = Object.hasOwn(properties, key); if (matched) next = this.convert(properties[key], base, next); - for (const [pattern, schema] of patterns) { + for (const [pattern, schema4] of patterns) { if (!pattern.test(key)) continue; matched = true; - next = this.convert(schema, base, next); + next = this.convert(schema4, base, next); } if (!matched && additional !== void 0) next = this.convert(additional, base, next); @@ -3865,19 +3865,19 @@ var Coercer = class { // --------------------------------------------------------------------------------------------------------------- // Pass 3: primitive coercion by type // --------------------------------------------------------------------------------------------------------------- - coerceTypes(value2, schema, base) { - if (!isSchemaObject(schema)) + coerceTypes(value2, schema4, base) { + if (!isSchemaObject(schema4)) return value2; - const b = this.baseOf(schema, base); + const b = this.baseOf(schema4, base); let next = value2; - if (Array.isArray(schema.allOf)) - for (const member of schema.allOf) + if (Array.isArray(schema4.allOf)) + for (const member of schema4.allOf) next = this.coerceTypes(next, member, b); - if (Array.isArray(schema.anyOf)) - next = this.coerceUnion(next, schema.anyOf, b); - if (Array.isArray(schema.oneOf)) - next = this.coerceUnion(next, schema.oneOf, b); - const types = typesOf(schema); + if (Array.isArray(schema4.anyOf)) + next = this.coerceUnion(next, schema4.anyOf, b); + if (Array.isArray(schema4.oneOf)) + next = this.coerceUnion(next, schema4.oneOf, b); + const types = typesOf(schema4); const matchesUnionMember = types.length > 1 && types.some((type) => matchesType(next, type)); if (types.length > 0 && !matchesUnionMember) { for (const type of types) { @@ -3889,9 +3889,9 @@ var Coercer = class { } } if (types.includes("object") && isPlainObject(next)) - next = this.coerceProperties(next, schema, b); + next = this.coerceProperties(next, schema4, b); if (types.includes("array") && Array.isArray(next)) - next = this.coerceItems(next, schema, b); + next = this.coerceItems(next, schema4, b); return next; } coerceUnion(value2, branches, base) { @@ -3905,12 +3905,12 @@ var Coercer = class { } return value2; } - coerceProperties(value2, schema, base) { - const properties = isSchemaObject(schema.properties) ? schema.properties : {}; - const patterns = isSchemaObject(schema.patternProperties) ? Object.entries(schema.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; - const additional = isSchemaObject(schema.additionalProperties) ? schema.additionalProperties : void 0; + coerceProperties(value2, schema4, base) { + const properties = isSchemaObject(schema4.properties) ? schema4.properties : {}; + const patterns = isSchemaObject(schema4.patternProperties) ? Object.entries(schema4.patternProperties).map(([pattern, item]) => [sharedRegex(pattern), item]) : []; + const additional = isSchemaObject(schema4.additionalProperties) ? schema4.additionalProperties : void 0; let out; - const set = (key, next) => { + const set2 = (key, next) => { if (next === (out ?? value2)[key]) return; out ??= { ...value2 }; @@ -3918,7 +3918,7 @@ var Coercer = class { }; for (const [key, property] of Object.entries(properties)) { if (key in value2) - set(key, this.coerceTypes(value2[key], property, base)); + set2(key, this.coerceTypes(value2[key], property, base)); } for (const key of Object.keys(value2)) { let matched = Object.hasOwn(properties, key); @@ -3926,31 +3926,31 @@ var Coercer = class { if (!pattern.test(key)) continue; matched = true; - set(key, this.coerceTypes((out ?? value2)[key], item, base)); + set2(key, this.coerceTypes((out ?? value2)[key], item, base)); } if (!matched && additional !== void 0) - set(key, this.coerceTypes(value2[key], additional, base)); + set2(key, this.coerceTypes(value2[key], additional, base)); } return out ?? value2; } - coerceItems(value2, schema, base) { + coerceItems(value2, schema4, base) { return mapItems(value2, (item, i) => { - const itemSchema = itemSchemaAt(schema, i); + const itemSchema = itemSchemaAt(schema4, i); return isSchemaObject(itemSchema) ? this.coerceTypes(item, itemSchema, base) : item; }); } }; -function itemSchemaAt(schema, index) { - if (Array.isArray(schema.items)) - return schema.items[index]; - if (Array.isArray(schema.prefixItems) && index < schema.prefixItems.length) - return schema.prefixItems[index]; - return schema.items; +function itemSchemaAt(schema4, index) { + if (Array.isArray(schema4.items)) + return schema4.items[index]; + if (Array.isArray(schema4.prefixItems) && index < schema4.prefixItems.length) + return schema4.prefixItems[index]; + return schema4.items; } -function mapItems(items, map2) { +function mapItems(items, map3) { let out; for (let i = 0; i < items.length; i++) { - const next = map2(items[i], i); + const next = map3(items[i], i); if (next === items[i]) continue; out ??= items.slice(); @@ -4046,11 +4046,11 @@ function tryNull(value2) { function isFiniteNumber(value2) { return typeof value2 === "number" && Number.isFinite(value2); } -function typesOf(schema) { - if (typeof schema.type === "string") - return [schema.type]; - if (Array.isArray(schema.type)) - return schema.type.filter((type) => typeof type === "string"); +function typesOf(schema4) { + if (typeof schema4.type === "string") + return [schema4.type]; + if (Array.isArray(schema4.type)) + return schema4.type.filter((type) => typeof type === "string"); return []; } function matchesType(value2, type) { @@ -4443,9 +4443,9 @@ function enumCheck(values) { return false; }; } - const set = new Set(primitives); + const set2 = new Set(primitives); const objects = values.filter((x) => typeof x === "object" && x !== null); - return (v) => set.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); + return (v) => set2.has(v) || typeof v === "object" && objects.some((o) => deepEqual(v, o)); } function constCheck(value2) { if (typeof value2 !== "object" || value2 === null) @@ -4704,9 +4704,9 @@ var Compiler = class { scope; cache = /* @__PURE__ */ new Map(); annotatingCache = /* @__PURE__ */ new Map(); - constructor(schema, options, dynamic) { - this.schema = schema; - this.r = new Resolver(schema, options); + constructor(schema4, options, dynamic) { + this.schema = schema4; + this.r = new Resolver(schema4, options); this.draft = this.r.draft; this.formats = options.formats; this.dynamic = dynamic; @@ -4772,9 +4772,9 @@ var Compiler = class { parts.push(bytesCheck(number(node.minLength) ?? 0, number(node.maxLength) ?? Number.POSITIVE_INFINITY)); typeInGroup = true; } else { - const string = this.stringGroup(node, single === "string"); - if (string !== void 0) - parts.push(string); + const string2 = this.stringGroup(node, single === "string"); + if (string2 !== void 0) + parts.push(string2); const numeric = single === "number" || single === "integer"; const number2 = this.numberGroup(node, single === "number" ? 1 : single === "integer" ? 2 : 0); if (number2 !== void 0) @@ -4785,7 +4785,7 @@ var Compiler = class { const array = this.arrayGroup(node, base, single === "array"); if (array !== void 0) parts.push(array); - typeInGroup = single === "string" && string !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; + typeInGroup = single === "string" && string2 !== void 0 || numeric && number2 !== void 0 || single === "object" && object !== void 0 || single === "array" && array !== void 0; } if (types !== void 0 && !typeInGroup) parts.unshift(typeCheck(types)); @@ -5194,9 +5194,9 @@ var Explainer = class { * to pick the one to blame, and every branch would explain the same children again, exponentially in the depth. */ memo = void 0; - constructor(compiler2, schema) { + constructor(compiler2, schema4) { this.c = compiler2; - this.schema = schema; + this.schema = schema4; compiler2.root(); } /** The errors of `value`, at least one (`value` failed the check). */ @@ -5548,9 +5548,9 @@ function typeName(v) { } // node_modules/@earendil-works/pi-schema/dist/validator.js -function compile(schema, options = NO_OPTIONS) { - const check2 = compileCheck(schema, options); - return options.coerce === true ? new CoercingValidator(schema, options, check2) : new Validator(schema, options, check2); +function compile(schema4, options = NO_OPTIONS) { + const check2 = compileCheck(schema4, options); + return options.coerce === true ? new CoercingValidator(schema4, options, check2) : new Validator(schema4, options, check2); } var NO_OPTIONS = Object.freeze({}); var Validator = class { @@ -5559,9 +5559,9 @@ var Validator = class { schema; options; explainer = void 0; - constructor(schema, options, check2) { + constructor(schema4, options, check2) { this.check = check2; - this.schema = schema; + this.schema = schema4; this.options = options; } /** @@ -5593,18 +5593,18 @@ var CoercingValidator = class extends Validator { return this.check(coerced) ? { ok: true, value: coerced } : { ok: false, errors: this.errors(coerced) }; } }; -function compileCheck(schema, options) { - return compiler(schema, options).root(); +function compileCheck(schema4, options) { + return compiler(schema4, options).root(); } -function compiler(schema, options) { - const plain = new Compiler(schema, options, false); +function compiler(schema4, options) { + const plain = new Compiler(schema4, options, false); try { plain.root(); return plain; } catch (error) { if (error !== RESTART) throw error; - return new Compiler(schema, options, true); + return new Compiler(schema4, options, true); } } @@ -5662,7 +5662,7 @@ async function runAll(steps, message) { } // node_modules/@earendil-works/chord/dist/schema.js -var asSchema = (schema) => schema !== null && typeof schema === "object" ? schema : schema === false ? { not: {} } : {}; +var asSchema = (schema4) => schema4 !== null && typeof schema4 === "object" ? schema4 : schema4 === false ? { not: {} } : {}; function canonicalJson(value2) { if (value2 === null || typeof value2 !== "object") return JSON.stringify(value2) ?? "null"; @@ -5685,34 +5685,34 @@ function deepEqual2(a, b) { return a === b || canonicalJson(a) === canonicalJson(b); } var validators = /* @__PURE__ */ new WeakMap(); -function validatorOf(schema) { - if (typeof schema === "boolean") - return compile(schema); - let validator = validators.get(schema); +function validatorOf(schema4) { + if (typeof schema4 === "boolean") + return compile(schema4); + let validator = validators.get(schema4); if (validator === void 0) { - validator = compile(schema); - validators.set(schema, validator); + validator = compile(schema4); + validators.set(schema4, validator); } return validator; } -function isValid(schema, value2) { - return validatorOf(schema).check(value2); +function isValid(schema4, value2) { + return validatorOf(schema4).check(value2); } -function assertValid(reason, what, schema, value2) { - const validator = validatorOf(schema); +function assertValid(reason, what, schema4, value2) { + const validator = validatorOf(schema4); if (validator.check(value2)) return; const errors = validator.errors(value2).slice(0, 3); const summary = errors.map((error) => `${error.path || "/"} ${error.message}`).join("; "); throw invalid(reason, `${what}: ${summary}`, errors); } -function normalize(schema, value2, what) { - const normalized = cleanFrom(asSchema(schema), withDefaults(asSchema(schema), cloneData(value2 ?? {}))); - assertValid("input", what, schema, normalized); +function normalize(schema4, value2, what) { + const normalized = cleanFrom(asSchema(schema4), withDefaults(asSchema(schema4), cloneData(value2 ?? {}))); + assertValid("input", what, schema4, normalized); return normalized; } -function cleaned(schema, value2) { - return cleanFrom(asSchema(schema), cloneData(value2)); +function cleaned(schema4, value2) { + return cleanFrom(asSchema(schema4), cloneData(value2)); } function cloneData(value2) { if (Array.isArray(value2)) @@ -5731,12 +5731,12 @@ function cloneData(value2) { } var isPlainObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2) && !(value2 instanceof Uint8Array); var isSchemaObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -function mergedAllOf(schema) { - if (!Array.isArray(schema.allOf) || !schema.allOf.every((branch) => isSchemaObject2(branch.properties))) +function mergedAllOf(schema4) { + if (!Array.isArray(schema4.allOf) || !schema4.allOf.every((branch) => isSchemaObject2(branch.properties))) return void 0; const properties = {}; const required = /* @__PURE__ */ new Set(); - for (const branch of schema.allOf) { + for (const branch of schema4.allOf) { Object.assign(properties, branch.properties); for (const key of branch.required ?? []) required.add(key); @@ -5745,22 +5745,22 @@ function mergedAllOf(schema) { type: "object", properties, required: [...required], - ...schema.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema.unevaluatedProperties } + ...schema4.unevaluatedProperties === void 0 ? {} : { additionalProperties: schema4.unevaluatedProperties } }; } -function recordOf(schema) { - if (!isSchemaObject2(schema.patternProperties) || isSchemaObject2(schema.properties)) +function recordOf(schema4) { + if (!isSchemaObject2(schema4.patternProperties) || isSchemaObject2(schema4.properties)) return void 0; - const [entry2] = Object.entries(schema.patternProperties); + const [entry2] = Object.entries(schema4.patternProperties); return entry2 === void 0 ? void 0 : [new RegExp(entry2[0], "u"), entry2[1]]; } var keepsUnknown = (additional, value2) => additional === true || isSchemaObject2(additional) && isValid(additional, value2); -function cleanFrom(schema, value2) { - const merged = mergedAllOf(schema); +function cleanFrom(schema4, value2) { + const merged = mergedAllOf(schema4); if (merged !== void 0) return cleanFrom(merged, value2); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = cleanFrom(asSchema(branch), cloneData(value2)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5768,42 +5768,42 @@ function cleanFrom(schema, value2) { return value2; } if (Array.isArray(value2)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { const length = Math.min(value2.length, prefix.length); for (let index = 0; index < length; index++) value2[index] = cleanFrom(asSchema(prefix[index]), value2[index]); return value2.length > length ? value2.slice(0, length) : value2; } - if (isSchemaObject2(schema.items)) - return value2.map((item) => cleanFrom(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return value2.map((item) => cleanFrom(schema4.items, item)); return value2; } if (!isPlainObject2(value2)) return value2; - const record2 = recordOf(schema); - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema.additionalProperties)) + const record2 = recordOf(schema4); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + if (properties === void 0 && record2 === void 0 && !isSchemaObject2(schema4.additionalProperties)) return value2; for (const key of Object.keys(value2)) { const known = properties !== void 0 && Object.hasOwn(properties, key) ? properties[key] : void 0; const matched = known ?? (record2?.[0].test(key) ? record2[1] : void 0); if (matched !== void 0) value2[key] = cleanFrom(asSchema(matched), value2[key]); - else if (keepsUnknown(schema.additionalProperties, value2[key])) - value2[key] = cleanFrom(asSchema(schema.additionalProperties), value2[key]); + else if (keepsUnknown(schema4.additionalProperties, value2[key])) + value2[key] = cleanFrom(asSchema(schema4.additionalProperties), value2[key]); else delete value2[key]; } return value2; } -function withDefaults(schema, value2) { - const defaulted = value2 === void 0 && "default" in schema ? cloneData(schema.default) : value2; - const merged = mergedAllOf(schema); +function withDefaults(schema4, value2) { + const defaulted = value2 === void 0 && "default" in schema4 ? cloneData(schema4.default) : value2; + const merged = mergedAllOf(schema4); if (merged !== void 0) return withDefaults(merged, defaulted); - if (Array.isArray(schema.anyOf)) { - for (const branch of schema.anyOf) { + if (Array.isArray(schema4.anyOf)) { + for (const branch of schema4.anyOf) { const candidate = withDefaults(asSchema(branch), cloneData(defaulted)); if (isValid(asSchema(branch), candidate)) return candidate; @@ -5811,7 +5811,7 @@ function withDefaults(schema, value2) { return defaulted; } if (Array.isArray(defaulted)) { - const prefix = Array.isArray(schema.items) ? schema.items : Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0; + const prefix = Array.isArray(schema4.items) ? schema4.items : Array.isArray(schema4.prefixItems) ? schema4.prefixItems : void 0; if (prefix !== void 0) { for (let index = 0; index < prefix.length; index++) { const item = withDefaults(asSchema(prefix[index]), defaulted[index]); @@ -5820,16 +5820,16 @@ function withDefaults(schema, value2) { } return defaulted; } - if (isSchemaObject2(schema.items)) - return defaulted.map((item) => withDefaults(schema.items, item)); + if (isSchemaObject2(schema4.items)) + return defaulted.map((item) => withDefaults(schema4.items, item)); return defaulted; } if (!isPlainObject2(defaulted)) return defaulted; - const properties = isSchemaObject2(schema.properties) ? schema.properties : void 0; - const record2 = recordOf(schema); + const properties = isSchemaObject2(schema4.properties) ? schema4.properties : void 0; + const record2 = recordOf(schema4); if (properties !== void 0) { - const required = schema.required ?? []; + const required = schema4.required ?? []; for (const [key, property] of Object.entries(properties)) { const item = withDefaults(asSchema(property), defaulted[key]); if (item === void 0 && (!required.includes(key) || !("default" in asSchema(property)))) @@ -5842,28 +5842,28 @@ function withDefaults(schema, value2) { defaulted[key] = withDefaults(record2[1], defaulted[key]); } } - if (!isSchemaObject2(schema.additionalProperties)) + if (!isSchemaObject2(schema4.additionalProperties)) return defaulted; for (const key of Object.keys(defaulted)) { const known = properties !== void 0 && Object.hasOwn(properties, key); if (!known && !record2?.[0].test(key)) - defaulted[key] = withDefaults(schema.additionalProperties, defaulted[key]); + defaulted[key] = withDefaults(schema4.additionalProperties, defaulted[key]); } return defaulted; } -function canonicalIdentity(schema, value2) { - return canonicalJson(stripDefaults(asSchema(schema), value2)); +function canonicalIdentity(schema4, value2) { + return canonicalJson(stripDefaults(asSchema(schema4), value2)); } -function stripDefaults(schema, value2) { +function stripDefaults(schema4, value2) { if (Array.isArray(value2)) { - const items = schema.items; + const items = schema4.items; if (Array.isArray(items)) return value2.map((item, index) => stripDefaults(asSchema(items[index]), item)); return value2.map((item) => stripDefaults(asSchema(items), item)); } if (value2 === null || typeof value2 !== "object") return value2; - const properties = asSchema(schema.properties); + const properties = asSchema(schema4.properties); const result = {}; for (const [key, item] of Object.entries(value2)) { const property = asSchema(properties[key]); @@ -5889,7 +5889,7 @@ var CONSTRAINTS = [ "minProperties", "maxProperties" ]; -var typesOf2 = (schema) => typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : void 0; +var typesOf2 = (schema4) => typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : void 0; var KNOWN = /* @__PURE__ */ new Set([ ...CONSTRAINTS, "type", @@ -5917,7 +5917,7 @@ var ANNOTATIONS = /* @__PURE__ */ new Set([ "writeOnly", "deprecated" ]); -var withoutAnnotations = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !ANNOTATIONS.has(key))); +var withoutAnnotations = (schema4) => Object.fromEntries(Object.entries(schema4).filter(([key]) => !ANNOTATIONS.has(key))); function fits(subSchema, supSchema) { const sub = withoutAnnotations(asSchema(subSchema)); const sup = withoutAnnotations(asSchema(supSchema)); @@ -6125,8 +6125,8 @@ function remote(name, def) { throw new TypeError(`remote contract ${name} has no variants`); for (const [kind, variant] of Object.entries(def.variants)) { const members = {}; - for (const [key, schema] of Object.entries(variant.state ?? {})) - members[key] = describeMember(key, schema, "remote"); + for (const [key, schema4] of Object.entries(variant.state ?? {})) + members[key] = describeMember(key, schema4, "remote"); for (const [key, spec] of Object.entries(variant.methods ?? {})) { if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`); @@ -9706,10 +9706,10 @@ var Source = class { validate(value2) { if (!this.options.dev) return; - for (const schema of this.ownSchemas()) - assertValid("state", `state ${this.key}`, schema, value2); - for (const schema of this.schemas) - assertValid("state", `state ${this.key}`, schema, value2); + for (const schema4 of this.ownSchemas()) + assertValid("state", `state ${this.key}`, schema4, value2); + for (const schema4 of this.schemas) + assertValid("state", `state ${this.key}`, schema4, value2); } ownSchemas() { return []; @@ -9750,11 +9750,11 @@ var Cell = class extends Source { * `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no * value until `initialize` (a cell declared with `init`, filled before its object goes live). */ - constructor(key, schema, initial, guard, options) { + constructor(key, schema4, initial, guard, options) { super(key, options); if (initial !== void 0) - assertValid("state", `initial value of state ${key}`, schema, initial.value); - this.schema = schema; + assertValid("state", `initial value of state ${key}`, schema4, initial.value); + this.schema = schema4; this.#tracker = track({ v: initial?.value ?? null }); this.#guard = guard; this.#initialized = initial !== void 0; @@ -9818,8 +9818,8 @@ var Cell = class extends Source { * Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations * over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset. */ - reset(value2, schema) { - this.schema = schema; + reset(value2, schema4) { + this.schema = schema4; this.#publish(this.#tracker.prepareReplace({ v: value2 }), "reset", false); } /** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */ @@ -9860,15 +9860,15 @@ function sharesStructure(a, b) { } function computeDependents(changed, value2, validate2 = true) { const pending = /* @__PURE__ */ new Set(); - const visit = (source) => { + const visit3 = (source) => { for (const derived of source.dependents) { if (pending.has(derived)) continue; pending.add(derived); - visit(derived); + visit3(derived); } }; - visit(changed); + visit3(changed); const values = /* @__PURE__ */ new Map([[changed, value2]]); const result = /* @__PURE__ */ new Map(); for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) { @@ -10372,8 +10372,8 @@ var MemberReadable = class { const source = this.#current(); return source === void 0 || hydrationOf(source)?.hydrated === false ? void 0 : source; } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); this.bind(); } #safe(fn) { @@ -10844,15 +10844,15 @@ var ObjectImpl = class { } /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */ refreshSchemas() { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); for (const installed of this.implementations.values()) { for (const [source, list] of memberSchemas(installed.service, installed.implementation)) { - schemas.set(source, [...schemas.get(source) ?? [], ...list]); + schemas2.set(source, [...schemas2.get(source) ?? [], ...list]); } } for (const decls of this.allDecls()) { for (const source of [...decls.cells.values(), ...decls.derives.values()]) - source.schemas = schemas.get(source) ?? []; + source.schemas = schemas2.get(source) ?? []; } } allDecls() { @@ -11113,8 +11113,8 @@ var ObjectImpl = class { throw new ChordError("not_in_variant", `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`); } const direct = view2 === installed.implementation; - const schema = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; - const method2 = schema?.kind === "method" ? schema : void 0; + const schema4 = direct ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name] : wanted; + const method2 = schema4?.kind === "method" ? schema4 : void 0; const validated = ref.contract.scope === "remote" ? method2 : void 0; const takesArgs = method2 === void 0 || method2.args !== void 0; const returns = method2 === void 0 || method2.result !== void 0; @@ -11225,16 +11225,16 @@ var ObjectImpl = class { this.stopTasks(); this.stopListeners(); await Promise.allSettled([...this.#invocations]); - const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime; + const registered = [...decls].some((set2) => set2.registrations.size > 0) && !this.deferredRuntime; this.implementations.clear(); this.decls = new Decls(); if (registered) this.host.registriesChanged(); const refs = /* @__PURE__ */ new Set(); - for (const set of decls) { - for (const derived of set.derives.values()) + for (const set2 of decls) { + for (const derived of set2.derives.values()) derived.detach(); - for (const ref of set.refs.values()) + for (const ref of set2.refs.values()) refs.add(ref); } try { @@ -11251,18 +11251,18 @@ var ObjectImpl = class { }; var isReadableLike = (value2) => value2 !== null && typeof value2 === "object" && typeof value2.events === "function" && typeof value2.subscribe === "function"; function memberSchemas(service2, implementation) { - const schemas = /* @__PURE__ */ new Map(); + const schemas2 = /* @__PURE__ */ new Map(); const contract = service2.contract; if (contract.scope !== "remote") - return schemas; + return schemas2; const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {}; for (const [name, description] of Object.entries(members)) { const source = implementation[name]; if (description.kind !== "state" || !isSource(source)) continue; - schemas.set(source, [...schemas.get(source) ?? [], description.schema]); + schemas2.set(source, [...schemas2.get(source) ?? [], description.schema]); } - return schemas; + return schemas2; } function validateImplementation(service2, implementation) { const contract = service2.contract; @@ -11307,13 +11307,13 @@ var SelfImpl = class { return { implementation, decls: this.#decls, created: this.#created }; } /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */ - #unique(map2, kind, name) { + #unique(map3, kind, name) { if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`); - if (map2.has(name)) + if (map3.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`); } - state(name, schema, initial, options = {}) { + state(name, schema4, initial, options = {}) { this.#unique(this.#decls.cells, "state", name); const version = options.version ?? 1; if (!Number.isInteger(version) || version < 1) @@ -11322,7 +11322,7 @@ var SelfImpl = class { const init = isStateInit(initial) ? initial.init : void 0; let cell = this.#previous?.cells.get(name); if (cell === void 0) { - cell = new Cell(name, schema, init === void 0 ? { value: initial } : void 0, this.#object.guard, { + cell = new Cell(name, schema4, init === void 0 ? { value: initial } : void 0, this.#object.guard, { dev: host2.dev, report: (error) => host2.report(error) }); @@ -11330,7 +11330,7 @@ var SelfImpl = class { this.#created.inits.push([cell, init]); } this.#decls.cells.set(name, cell); - this.#decls.cellSchemas.set(name, schema); + this.#decls.cellSchemas.set(name, schema4); this.#decls.cellVersions.set(name, version); if (options.migrate !== void 0) this.#decls.cellMigrations.set(name, options.migrate); @@ -11432,15 +11432,15 @@ function dryRun(candidate) { const { run: run2, migrated, service: service2, object } = candidate; const exposed = memberSchemas(service2, run2.implementation); for (const [cell, value2] of migrated) { - for (const schema of exposed.get(cell) ?? []) - assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value2); + for (const schema4 of exposed.get(cell) ?? []) + assertValid("state", `${object.address}: migrated state ${cell.key}`, schema4, value2); } const values = new Map(migrated); const derives = [...run2.decls.derives].sort(([, a], [, b]) => a.seq - b.seq); for (const [name, derived] of derives) { const value2 = derived.compute((source) => values.has(source) ? values.get(source) : candidateValue(source)); - for (const schema of exposed.get(derived) ?? []) - assertValid("state", `${object.address}: derivation ${name}`, schema, value2); + for (const schema4 of exposed.get(derived) ?? []) + assertValid("state", `${object.address}: derivation ${name}`, schema4, value2); values.set(derived, value2); } candidate.derived = values; @@ -11806,17 +11806,17 @@ var Reload = class { for (const [name, cell] of run2.decls.cells) { if (object.decls.cells.get(name) !== cell) continue; - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); const from = object.decls.cellVersions.get(name) ?? 1; const fn = run2.decls.cellMigrations.get(name); let value2; if ((run2.decls.cellVersions.get(name) ?? 1) > from && fn !== void 0) value2 = fn(structuredClone(cell.value), from); - else if (!deepEqual2(cell.schema, schema)) + else if (!deepEqual2(cell.schema, schema4)) value2 = cell.value; else continue; - assertValid("state", `${object.address}: migrated state ${name}`, schema, value2); + assertValid("state", `${object.address}: migrated state ${name}`, schema4, value2); candidate.migrated.set(cell, value2); } dryRun(candidate); @@ -11988,11 +11988,11 @@ var Reload = class { } object.refreshSchemas(); for (const [name, cell] of run2.decls.cells) { - const schema = run2.decls.cellSchemas.get(name); + const schema4 = run2.decls.cellSchemas.get(name); if (candidate.migrated.has(cell)) - cell.reset(candidate.migrated.get(cell), schema); + cell.reset(candidate.migrated.get(cell), schema4); else - cell.schema = schema; + cell.schema = schema4; } const created = new Set(run2.created.derives); for (const derived of run2.created.derives) @@ -13889,10 +13889,10 @@ var RemoteBinding = class { removeView(view2) { if (!this.views.delete(view2)) return; - for (const set of this.#listeners.values()) - for (const readable of set) + for (const set2 of this.#listeners.values()) + for (const readable of set2) if (readable.view === view2) - set.delete(readable); + set2.delete(readable); if (this.views.size === 0) { this.host.bindingIdle(this); return; @@ -13919,12 +13919,12 @@ var RemoteBinding = class { view2.update(); } listen(name, readable) { - let set = this.#listeners.get(name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#listeners.set(name, set); + let set2 = this.#listeners.get(name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#listeners.set(name, set2); } - set.add(readable); + set2.add(readable); } unlisten(name, readable) { this.#listeners.get(name)?.delete(readable); @@ -14203,8 +14203,8 @@ var ViewReadable = class { if (!this.view.ended) this.view.binding.listen(this.#name, this); } - #remove(set, listener) { - set.delete(listener); + #remove(set2, listener) { + set2.delete(listener); if (this.#values.size + this.#events.size === 0) this.view.binding.unlisten(this.#name, this); } @@ -14633,11 +14633,11 @@ var HostImpl = class { * the host principal, whoever asks; another input is invalid. */ #locate(service2, input, principal) { - const { name, input: schema } = service2.contract; - const normalized = normalize(schema, input, `${name} input`); - const identity = canonicalIdentity(schema, normalized); + const { name, input: schema4 } = service2.contract; + const normalized = normalize(schema4, input, `${name} input`); + const identity = canonicalIdentity(schema4, normalized); if (hostLifetime(service2)) { - if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`))) + if (identity !== canonicalIdentity(schema4, normalize(schema4, {}, `${name} input`))) throw invalid("input", `${name} has lifetime "host": its one object has the empty input`); principal = this.principal; } @@ -14885,15 +14885,15 @@ var HostImpl = class { table, get: (key, ctx) => table(ctx).get(key), subscribe: (listener) => { - let set = this.#subscribers.get(registry2.name); - if (set === void 0) { - set = /* @__PURE__ */ new Set(); - this.#subscribers.set(registry2.name, set); + let set2 = this.#subscribers.get(registry2.name); + if (set2 === void 0) { + set2 = /* @__PURE__ */ new Set(); + this.#subscribers.set(registry2.name, set2); } const wrapped = listener; - set.add(wrapped); + set2.add(wrapped); wrapped(table(), this.current.id); - return () => set.delete(wrapped); + return () => set2.delete(wrapped); } }; } @@ -16488,19 +16488,19 @@ var ConversationTails = class { return this.#markers.size; } }; -function use(map2, key) { - const value2 = map2.get(key); +function use(map3, key) { + const value2 = map3.get(key); if (value2 === void 0) return void 0; - map2.delete(key); - map2.set(key, value2); + map3.delete(key); + map3.set(key, value2); return value2; } -function put(map2, key, value2, capacity) { - map2.delete(key); - map2.set(key, value2); - if (map2.size > capacity) - map2.delete(map2.keys().next().value); +function put(map3, key, value2, capacity) { + map3.delete(key); + map3.set(key, value2); + if (map3.size > capacity) + map3.delete(map3.keys().next().value); } function freeze2(value2) { if (value2 === null || typeof value2 !== "object" || Object.isFrozen(value2)) @@ -17259,14 +17259,14 @@ var Transaction = class { this.#writes.splice(at, 0, write); } /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */ - adopt(seq) { + adopt(seq2) { const publications = []; let stored; for (const plan of this.#plans) { const committed = "createdAt" in plan.record; - let record2 = committed ? plan.record : { ...plan.record, createdAt: seq }; + let record2 = committed ? plan.record : { ...plan.record, createdAt: seq2 }; if (plan.retire) - record2 = { ...record2, retiredAt: seq }; + record2 = { ...record2, retiredAt: seq2 }; const change = plan.change; if (change !== void 0) { const { tracker, prepared, loaded, version } = change; @@ -17714,8 +17714,8 @@ var Writer = class { } if (stored.length > 0) { try { - result = await this.#host.commit(stored.map((part) => part.writes), (index, seq) => { - seqs[index] = seq; + result = await this.#host.commit(stored.map((part) => part.writes), (index, seq2) => { + seqs[index] = seq2; }, withoutAbortSignal(stored[0].context)); } catch (error) { rejected = { error }; @@ -17748,8 +17748,8 @@ var Writer = class { failing.push({ part, outcome, published: false }); continue; } - const seq = index === void 0 ? void 0 : seqs[index]; - if (index !== void 0 && seq === void 0) { + const seq2 = index === void 0 ? void 0 : seqs[index]; + if (index !== void 0 && seq2 === void 0) { const error = rejected !== void 0 ? rejected.error : index === result?.stored && "refused" in result ? result.refused : new Error("Storage committed without adopting the batch"); failing.push({ part, outcome: { kind: "own", error }, published: false }); stop2 = { error, at: part.index }; @@ -17767,7 +17767,7 @@ var Writer = class { try { if (part.writes !== void 0) this.#host.stored(part.writes); - failure2 = part.publish(seq); + failure2 = part.publish(seq2); } catch (error) { failure2 = { kind: "adoption", error }; } @@ -18632,7 +18632,7 @@ var SessionImpl = class { writes, keys, context, - publish: (seq) => this.#adopt(tx, writes, taken, seq, context), + publish: (seq2) => this.#adopt(tx, writes, taken, seq2, context), discard }); this.#sweepDocuments(); @@ -18642,15 +18642,15 @@ var SessionImpl = class { * Publish a stored commit (`Writer`), after the read caches took its writes: adopt it in memory and run its * publication. A throw of the adoption leaves memory behind durable state; the writer fails the Session with it. */ - #adopt(tx, writes, taken, seq, context) { + #adopt(tx, writes, taken, seq2, context) { let documents; try { - documents = tx.adopt(seq); + documents = tx.adopt(seq2); } catch (error) { return { kind: "adoption", error }; } - this.#indexTaskDocuments(tx, writes, documents, seq); - const failure = this.#publish(seq, writes, documents, context); + this.#indexTaskDocuments(tx, writes, documents, seq2); + const failure = this.#publish(seq2, writes, documents, context); if (taken.length > 0) this.#release(taken); for (const document of documents.stored) @@ -18661,7 +18661,7 @@ var SessionImpl = class { * At publication: keep `#taskDocuments` in step with a stored commit: the tasks it creates start with no documents, * task documents it creates join their task, ones it retires leave, and tasks it ends leave the index. */ - #indexTaskDocuments(tx, writes, documents, seq) { + #indexTaskDocuments(tx, writes, documents, seq2) { for (const id of tx.createdTaskIds()) this.#taskDocuments.set(id, /* @__PURE__ */ new Map()); if (this.#taskDocuments.size === 0) @@ -18674,7 +18674,7 @@ var SessionImpl = class { continue; if (change.kind === "retire") known.delete(change.record.id); - else if (change.record.createdAt === seq) + else if (change.record.createdAt === seq2) known.set(change.record.id, change.record); } for (const write of writes) { @@ -18743,7 +18743,7 @@ var SessionImpl = class { const conversationId = record2.scope.kind === "conversation" ? record2.scope.conversationId : void 0; changes.push({ type: "document", kind: "change", record: record2, conversationId, version, value: value2, ops: stored.ops }); } - const publish2 = (seq) => { + const publish2 = (seq2) => { for (const [index2, hold] of holds.entries()) { if (writes[index2].content.kind === "base") hold.loaded.deltasSinceBase = 0; @@ -18751,7 +18751,7 @@ var SessionImpl = class { hold.loaded.deltasSinceBase++; } if (this.#commitListeners.size > 0) - this.#notifyHosts({ seq, changes }, context); + this.#notifyHosts({ seq: seq2, changes }, context); this.#release(holds); return void 0; }; @@ -18806,7 +18806,7 @@ var SessionImpl = class { * observers, queued before the waits and aborts the observers wake, then the Session's own observers. Never throws: * returns the first error of an own observer, which fails the Session once its storage call settled. */ - #publish(seq, writes, documents, context) { + #publish(seq2, writes, documents, context) { const changes = this.#commitListeners.size > 0 || this.#internalListeners.size > 0 ? [] : void 0; for (const write of writes) { switch (write.type) { @@ -18834,9 +18834,9 @@ var SessionImpl = class { const tables = changes.length; for (const document of documents.observed) changes.push(document); - const observed = { kind: "stored", seq, changes }; + const observed = { kind: "stored", seq: seq2, changes }; if (this.#commitListeners.size > 0) { - const stored = documents.stored === documents.observed ? observed : { seq, changes: [...changes.slice(0, tables), ...documents.stored] }; + const stored = documents.stored === documents.observed ? observed : { seq: seq2, changes: [...changes.slice(0, tables), ...documents.stored] }; this.#notifyHosts(stored, context); } let failure; @@ -19467,7 +19467,7 @@ async function addTools(tx, conversationId, added) { state.modelTools = { ...remove.length === 0 ? {} : { remove }, add }; } function applyChange(state, change) { - const set = (key, value2) => { + const set2 = (key, value2) => { if (value2 === void 0) return; if (value2 === null) @@ -19475,27 +19475,27 @@ function applyChange(state, change) { else state[key] = value2; }; - set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); - set("thinkingLevel", change.thinkingLevel); + set2("model", change.model === void 0 || change.model === null ? change.model : { ...change.model }); + set2("thinkingLevel", change.thinkingLevel); const extensions = change.extensions; - set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { + set2("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : { ...extensions.add === void 0 ? {} : { add: names(extensions.add) }, ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) } }); const tools = change.tools; - set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); + set2("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) }); const modelTools = change.modelTools; - set("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { + set2("modelTools", modelTools === void 0 || modelTools === null ? modelTools : isList(modelTools) ? names(modelTools) : { ...modelTools.remove === void 0 ? {} : { remove: names(modelTools.remove) }, ...modelTools.add === void 0 ? {} : { add: names(modelTools.add) } }); - set("instructions", change.instructions); - set("cwd", change.cwd); + set2("instructions", change.instructions); + set2("cwd", change.cwd); const maxTurns = change.maxTurns; if (maxTurns !== void 0 && maxTurns !== null && !(Number.isSafeInteger(maxTurns) && maxTurns >= 1)) { throw new RangeError(`maxTurns must be an integer 1 or more, got ${String(maxTurns)}`); } - set("maxTurns", maxTurns); + set2("maxTurns", maxTurns); } function isList(value2) { return Array.isArray(value2); @@ -20100,7 +20100,7 @@ function orderToolResults(messages) { } return ordered; } -function missingResult(call2, timestamp) { +function missingResult(call2, timestamp2) { return freezeJson({ role: "toolResult", toolCallId: call2.id, @@ -20108,7 +20108,7 @@ function missingResult(call2, timestamp) { content: [{ type: "text", text: MISSING_RESULT_TEXT }], isError: true, details: { reason: "missing_result" }, - timestamp + timestamp: timestamp2 }); } @@ -20529,21 +20529,21 @@ ${text} } return desired; } -function planSystemEntries(view2, desired, tools, timestamp) { +function planSystemEntries(view2, desired, tools, timestamp2) { const head = view2.head; if (head !== void 0 && !view2.entries.some((entry2) => SystemEntry.is(entry2) && entry2.id > head.id)) { const edits = view2.entries.filter((entry2) => SystemEntry.is(entry2)).map((entry2) => ({ target: entry2.id, action: "omit" })); - const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp); + const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp2); return [edits.length === 0 ? baseline : { ...baseline, edits }]; } const sections = planSections(replaySections(view2.messages), desired); const changes = planTools(getCurrentTools(view2.messages), tools); if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) { - return sections.map((patch) => systemEntry(patch, void 0, timestamp)); + return sections.map((patch) => systemEntry(patch, void 0, timestamp2)); } if (sections.length === 0) - return [systemEntry(void 0, changes, timestamp)]; - return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp)); + return [systemEntry(void 0, changes, timestamp2)]; + return sections.map((patch, index) => systemEntry(patch, index === sections.length - 1 ? changes : void 0, timestamp2)); } function planTools(offered, desired) { const wanted = new Map(desired.map((tool) => [tool.name, tool])); @@ -20585,14 +20585,14 @@ function planSections(shown, desired) { patch[key] = value2; return Object.keys(patch).length === 0 ? [] : [patch]; } -function systemEntry(sections, tools, timestamp) { +function systemEntry(sections, tools, timestamp2) { const message = { role: "system", content: "", ...sections === void 0 ? {} : { sections }, ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved }, ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded }, - timestamp + timestamp: timestamp2 }; return { model: [message] }; } @@ -20619,9 +20619,9 @@ function uuidv7(timestampMs) { throw new RangeError("UUIDv7 generator sequence exhausted"); sequence2++; } - const timestamp = BigInt(effectiveTimestamp); + const timestamp2 = BigInt(effectiveTimestamp); for (let index = 5; index >= 0; index--) { - bytes2[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255; + bytes2[index] = Number(timestamp2 >> BigInt((5 - index) * 8)) & 255; } bytes2[6] = 112 | Number(sequence2 >> 37n & 0x0fn); bytes2[7] = Number(sequence2 >> 29n & 0xffn); @@ -20800,12 +20800,12 @@ var Waiters = class { if (signal?.aborted) return Promise.reject(signal.reason); const waiter = Promise.withResolvers(); - const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); - this.#sets.set(key, set.add(waiter)); + const set2 = this.#sets.get(key) ?? /* @__PURE__ */ new Set(); + this.#sets.set(key, set2.add(waiter)); if (signal !== void 0) { const onAbort = () => { - set.delete(waiter); - if (set.size === 0 && this.#sets.get(key) === set) + set2.delete(waiter); + if (set2.size === 0 && this.#sets.get(key) === set2) this.#sets.delete(key); waiter.reject(signal.reason); }; @@ -20819,16 +20819,16 @@ var Waiters = class { return [...this.#sets.keys()]; } resolve(key, value2) { - const set = this.#sets.get(key); + const set2 = this.#sets.get(key); this.#sets.delete(key); - for (const waiter of set ?? []) + for (const waiter of set2 ?? []) waiter.resolve(value2); } rejectAll(error) { const sets = [...this.#sets.values()]; this.#sets.clear(); - for (const set of sets) - for (const waiter of set) + for (const set2 of sets) + for (const waiter of set2) waiter.reject(error); } }; @@ -23413,20 +23413,20 @@ function overlayOf(tx) { const edges = new Map(tx.stagedConversations().map((record2) => [record2.id, record2.owner?.taskId ?? null])); return { tasks, edges }; } -function addTo(map2, key, value2) { - const values = map2.get(key); +function addTo(map3, key, value2) { + const values = map3.get(key); if (values === void 0) - map2.set(key, /* @__PURE__ */ new Set([value2])); + map3.set(key, /* @__PURE__ */ new Set([value2])); else values.add(value2); } -function deleteFrom(map2, key, value2) { - const values = map2.get(key); +function deleteFrom(map3, key, value2) { + const values = map3.get(key); if (values === void 0) return; values.delete(value2); if (values.size === 0) - map2.delete(key); + map3.delete(key); } function memoOf(record2, name) { const memos = record2?.memos; @@ -24334,13 +24334,13 @@ var formats = Object.freeze({ // node_modules/@earendil-works/pi-ai/dist/utils/validation.js var validatorCache = /* @__PURE__ */ new WeakMap(); -function getValidator(schema) { - const cached = validatorCache.get(schema); +function getValidator(schema4) { + const cached = validatorCache.get(schema4); if (cached) { return cached; } - const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" }); - validatorCache.set(schema, validator); + const validator = compile(schema4, { formats, coerce: true, unresolvedRefs: "reject" }); + validatorCache.set(schema4, validator); return validator; } function formatValidationPath(pointer2) { @@ -24942,18 +24942,18 @@ async function afterHarnessResult(runtime, input, call2, tool, result, truncatio } var structuredValidators = /* @__PURE__ */ new WeakMap(); function structuredOutputError(tool, result) { - const schema = tool.structuredOutputSchema; + const schema4 = tool.structuredOutputSchema; const value2 = result.structuredOutput; - if (schema === void 0) { + if (schema4 === void 0) { return value2 === void 0 ? void 0 : `Tool ${tool.name} returned structuredOutput but declares no structuredOutputSchema`; } if (value2 === void 0) { return result.isError === true ? void 0 : `Tool ${tool.name} returned no structuredOutput`; } - let validator = structuredValidators.get(schema); + let validator = structuredValidators.get(schema4); if (validator === void 0) { - validator = compile(schema, { formats, unresolvedRefs: "reject" }); - structuredValidators.set(schema, validator); + validator = compile(schema4, { formats, unresolvedRefs: "reject" }); + structuredValidators.set(schema4, validator); } if (validator.check(value2)) return void 0; @@ -25133,7 +25133,7 @@ function errorTextOf(result, output) { return output.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n"); } async function appendToolResult(tx, conversationId, call2, result, meta) { - const { timestamp, durationMs } = meta; + const { timestamp: timestamp2, durationMs } = meta; const diagnostics = [...result.diagnostics ?? []]; const content = [...result.output ?? []]; if (diagnostics.length > 0) @@ -25147,7 +25147,7 @@ async function appendToolResult(tx, conversationId, call2, result, meta) { ...result.usage === void 0 ? {} : { usage: result.usage }, isError: result.isError ?? false, ...durationMs === void 0 ? {} : { durationMs }, - timestamp + timestamp: timestamp2 }; if (result.usage !== void 0) await recordUsage(tx, conversationId, "tools", call2.name, result.usage); @@ -28084,16 +28084,16 @@ var MemoryStorage = class { seqs.push(prepared.apply()); } } finally { - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); } return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } /** Validate and detach one commit without changing observable state. */ - prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) { + prepareCommit(writes, seq2 = seqFromNumber(this.nextSeq)) { this.assertOpen(); - if (!Number.isSafeInteger(seq) || seq < this.nextSeq) { - throw new Error(`Commit sequence ${seq} does not strictly increase`); + if (!Number.isSafeInteger(seq2) || seq2 < this.nextSeq) { + throw new Error(`Commit sequence ${seq2} does not strictly increase`); } const detachedWrites = freeze3(this.resolveDocumentCopies(writes.map((write) => clone(write)))); this.checkGlobalIds(detachedWrites); @@ -28101,14 +28101,14 @@ var MemoryStorage = class { this.checkDocumentActions(documentActions); let applied = false; return { - seq, + seq: seq2, writes: detachedWrites, apply: () => { if (!applied) { applied = true; - this.applyPreparedCommit(detachedWrites, documentActions, seq); + this.applyPreparedCommit(detachedWrites, documentActions, seq2); } - return seq; + return seq2; } }; } @@ -28146,7 +28146,7 @@ var MemoryStorage = class { } }); } - applyPreparedCommit(prepared, documentActions, seq) { + applyPreparedCommit(prepared, documentActions, seq2) { for (const write of prepared) { switch (write.type) { case "conversation": { @@ -28164,7 +28164,7 @@ var MemoryStorage = class { case "entry": { this.state.recordTypes.set(write.value.id, "entry"); this.state.entries.set(write.value.id, write.value); - this.state.entryCommitSeqs.set(write.value.id, seq); + this.state.entryCommitSeqs.set(write.value.id, seq2); let ids = this.state.entryIds.get(write.value.conversationId); if (ids === void 0) { ids = []; @@ -28234,9 +28234,9 @@ var MemoryStorage = class { break; } } - this.applyDocumentActions(documentActions, seq); - this.nextSeq = seq + 1; - return seq; + this.applyDocumentActions(documentActions, seq2); + this.nextSeq = seq2 + 1; + return seq2; } async mintId() { this.assertOpen(); @@ -28579,16 +28579,16 @@ var MemoryStorage = class { throw new Error(`Document address already has a current incarnation`); } } - applyDocumentActions(actions, seq) { + applyDocumentActions(actions, seq2) { for (const [id, action] of actions) { let stored = this.state.documents.get(id); if (action.create !== void 0) { const record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; - stored = { record: record2, revisions: [{ ...action.content, seq }] }; + stored = { record: record2, revisions: [{ ...action.content, seq: seq2 }] }; this.state.recordTypes.set(id, "document"); this.state.documents.set(id, stored); const key = recordAddressKey(record2); @@ -28606,14 +28606,14 @@ var MemoryStorage = class { insertSorted(scopeIds, id); this.nextId = Math.max(this.nextId, id + 1); } else if (action.content !== void 0) { - const revision = { ...action.content, seq }; + const revision = { ...action.content, seq: seq2 }; if (revision.kind === "base" && isCurrentOnly(stored.record)) stored.revisions = [revision]; else stored.revisions.push(revision); } if (action.retire && action.create === void 0) - stored.record = { ...stored.record, retiredAt: seq }; + stored.record = { ...stored.record, retiredAt: seq2 }; if (action.retire && isCurrentOnly(stored.record)) stored.revisions = []; if (action.create !== void 0 || action.retire) { @@ -28631,6 +28631,6646 @@ var MemoryStorage = class { } }; +// node_modules/yaml/browser/index.js +var browser_exports = {}; +__export(browser_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + default: () => browser_default, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/index.js +var dist_exports4 = {}; +__export(dist_exports4, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync +}); + +// node_modules/yaml/browser/dist/nodes/identity.js +var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); +var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); +var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); +var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); +var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); +var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); +var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); +var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; +var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; +} +var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + +// node_modules/yaml/browser/dist/visit.js +var BREAK = /* @__PURE__ */ Symbol("break visit"); +var SKIP = /* @__PURE__ */ Symbol("skip children"); +var REMOVE = /* @__PURE__ */ Symbol("remove node"); +function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit.BREAK = BREAK; +visit.SKIP = SKIP; +visit.REMOVE = REMOVE; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK; +visitAsync.SKIP = SKIP; +visitAsync.REMOVE = REMOVE; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} + +// node_modules/yaml/browser/dist/doc/directives.js +var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy2 = new _Directives(this.yaml, this.tags); + copy2.docStart = this.docStart; + return copy2; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid2 = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid2); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines2 = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines2.push(`%TAG ${handle} ${prefix}`); + } + return lines2.join("\n"); + } +}; +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + +// node_modules/yaml/browser/dist/doc/anchors.js +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root2) { + const anchors = /* @__PURE__ */ new Set(); + visit(root2, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} + +// node_modules/yaml/browser/dist/doc/applyReviver.js +function applyReviver(reviver, obj2, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj2, key, val); +} + +// node_modules/yaml/browser/dist/nodes/toJS.js +function toJS(value2, arg, ctx) { + if (Array.isArray(value2)) + return value2.map((v, i) => toJS(v, String(i), ctx)); + if (value2 && typeof value2.toJSON === "function") { + if (!ctx || !hasAnchor(value2)) + return value2.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value2, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value2.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value2 === "bigint" && !ctx?.keep) + return Number(value2); + return value2; +} + +// node_modules/yaml/browser/dist/nodes/Node.js +var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } +}; + +// node_modules/yaml/browser/dist/nodes/Alias.js +var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors, doc: doc2, maxAliasCount } = ctx; + let data = anchors.get(found); + if (!data) { + toJS(found, null, ctx); + data = anchors.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } +}; +function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) + count = c; + } + return count; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; +} + +// node_modules/yaml/browser/dist/nodes/Scalar.js +var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object"; +var Scalar = class extends NodeBase { + constructor(value2) { + super(SCALAR); + this.value = value2; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar.PLAIN = "PLAIN"; +Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + +// node_modules/yaml/browser/dist/doc/createNode.js +var defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value2, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value2) && !t.format); +} +function createNode2(value2, tagName, ctx) { + if (isDocument(value2)) + value2 = value2.contents; + if (isNode(value2)) + return value2; + if (isPair(value2)) { + const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value2); + return map3; + } + if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) { + value2 = value2.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value2 && typeof value2 === "object") { + ref = sourceObjects.get(value2); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value2)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value2, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value2, tagName, schema4.tags); + if (!tagObj) { + if (value2 && typeof value2.toJSON === "function") { + value2 = value2.toJSON(); + } + if (!value2 || typeof value2 !== "object") { + const node2 = new Scalar(value2); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value2 instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value2) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} + +// node_modules/yaml/browser/dist/nodes/Collection.js +function collectionFromPath(schema4, path, value2) { + let v = value2; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); + } + } + return createNode2(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy2.schema = schema4; + copy2.items = copy2.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value2) { + if (isEmptyPath(path)) + this.add(value2); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value2); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value2); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value2)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyComment.js +var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment; + +// node_modules/yaml/browser/dist/stringify/foldFlowLines.js +var FOLD_FLOW = "flow"; +var FOLD_BLOCK = "block"; +var FOLD_QUOTED = "quoted"; +function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} + +// node_modules/yaml/browser/dist/stringify/stringifyString.js +var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2); +function lineLengthOverLimit(str2, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str2.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str2[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value2, ctx) { + const json = JSON.stringify(value2); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + let str2 = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str2 += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str2 += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str2 += "\\0"; + break; + case "0007": + str2 += "\\a"; + break; + case "000b": + str2 += "\\v"; + break; + case "001b": + str2 += "\\e"; + break; + case "0085": + str2 += "\\N"; + break; + case "00a0": + str2 += "\\_"; + break; + case "2028": + str2 += "\\L"; + break; + case "2029": + str2 += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str2 += "\\x" + code.substr(2); + else + str2 += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str2 += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str2 += "\n"; + i += 2; + } + str2 += indent; + if (json[i + 2] === " ") + str2 += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str2 = start ? str2 + json.slice(start) : json; + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value2, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2)) + return doubleQuotedString(value2, ctx); + const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : ""); + const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value2, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value2.includes('"'); + const hasSingle = value2.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value2, ctx); +} +var blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value2.length; endStart > 0; --endStart) { + const ch = value2[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value2.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value2 === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value2 = value2.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value2.length; ++startEnd) { + const ch = value2[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value2 = value2.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value2 = value2.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value2}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value: value2 } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) { + return quotedString(value2, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) { + return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value2)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value2, ctx); + } + } + const str2 = value2.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value2, ctx); + } + return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} + +// node_modules/yaml/browser/dist/stringify/stringify.js +function createStringifyContext(doc, options) { + const opt2 = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt2.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt2.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ", + inFlow, + options: opt2 + }; +} +function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj2; + if (isScalar(item)) { + obj2 = item.value; + let match = tags.filter((t) => t.identify?.(obj2)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj2 = item; + tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str2; + return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props} +${ctx.indent}${str2}`; +} + +// node_modules/yaml/browser/dist/stringify/stringifyPair.js +function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str2 = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str2.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value2 == null) { + if (keyCommentDone && onComment) + onComment(); + return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2; + } + } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) { + str2 = `? ${str2}`; + if (keyComment && !keyCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + str2 = `? ${str2} +${indent}:`; + } else { + str2 = `${str2}:`; + if (keyComment) + str2 += lineComment(str2, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode(value2)) { + vsb = !!value2.spaceBefore; + vcb = value2.commentBefore; + valueComment = value2.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value2 && typeof value2 === "object") + value2 = doc.createNode(value2); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value2)) + ctx.indentAtStart = str2.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value2)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str2 += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str2 += lineComment(str2, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str2; +} + +// node_modules/yaml/browser/dist/log.js +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } +} + +// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +var MERGE_KEY = "<<"; +var merge3 = { + identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +var isMergeKey = (ctx, key) => (merge3.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); +function addMergeToJSMap(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); +} +function mergeValue(ctx, map3, value2) { + const source = resolveAliasValue(ctx, value2); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value3] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value3); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value3, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map3; +} +function resolveAliasValue(ctx, value2) { + return ctx && isAlias(value2) ? value2.resolve(ctx.doc, ctx) : value2; +} + +// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +function addPairToJSMap(ctx, map3, { key, value: value2 }) { + if (isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value2); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map3, value2); + else { + const jsKey = toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS(value2, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value2, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } + } + return map3; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} + +// node_modules/yaml/browser/dist/nodes/Pair.js +function createPair(key, value2, ctx) { + const k = createNode2(key, void 0, ctx); + const v = createNode2(value2, void 0, ctx); + return new Pair(k, v); +} +var Pair = class _Pair { + constructor(key, value2 = null) { + Object.defineProperty(this, NODE_TYPE, { value: PAIR }); + this.key = key; + this.value = value2; + } + clone(schema4) { + let { key, value: value2 } = this; + if (isNode(key)) + key = key.clone(schema4); + if (isNode(value2)) + value2 = value2.clone(schema4); + return new _Pair(key, value2); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyCollection.js +function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str3 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str3 += lineComment(str3, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines2.push(blockItemPrefix + str3); + } + let str2; + if (lines2.length === 0) { + str2 = flowChars.start + flowChars.end; + } else { + str2 = lines2[0]; + for (let i = 1; i < lines2.length; ++i) { + const line = lines2[i]; + str2 += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str2 += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str2; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines2 = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (isNode(item)) { + if (item.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines2.push(""); + addCommentBefore(ctx, lines2, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str2 = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines2.length > linesAtValue || str2.includes("\n")); + if (i < items.length - 1) { + str2 += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines2.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str2 += ","; + } + } + if (comment) + str2 += lineComment(str2, itemIndent, commentString(comment)); + lines2.push(str2); + linesAtValue = lines2.length; + } + const { start, end } = flowChars; + if (lines2.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines2.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str2 = start; + for (const line of lines2) + str2 += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str2} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines2.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines2, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines2.push(ic.trimStart()); + } +} + +// node_modules/yaml/browser/dist/nodes/YAMLMap.js +function findPair(items, key) { + const k = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj2, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema4); + const add = (key, value2) => { + if (typeof replacer === "function") + value2 = replacer.call(obj2, key, value2); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value2 !== void 0 || keepUndefined) + map3.items.push(createPair(key, value2, ctx)); + }; + if (obj2 instanceof Map) { + for (const [key, value2] of obj2) + add(key, value2); + } else if (obj2 && typeof obj2 === "object") { + for (const key of Object.keys(obj2)) + add(key, obj2[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map3.items.sort(schema4.sortMapEntries); + } + return map3; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value2) { + this.add(new Pair(key, value2), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap(ctx, map3, item); + return map3; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; + +// node_modules/yaml/browser/dist/schema/common/map.js +var map2 = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map3, onError) { + if (!isMap(map3)) + onError("Expected a mapping for this tag"); + return map3; + }, + createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/nodes/YAMLSeq.js +var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value2) { + this.items.push(value2); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value2) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value2)) + prev.value = value2; + else + this.items[idx] = value2; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj2, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj2 && Symbol.iterator in Object(obj2)) { + let i = 0; + for (let it of obj2) { + if (typeof replacer === "function") { + const key = obj2 instanceof Set ? it : String(i++); + it = replacer.call(obj2, key, it); + } + seq2.items.push(createNode2(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} + +// node_modules/yaml/browser/dist/schema/common/seq.js +var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx) +}; + +// node_modules/yaml/browser/dist/schema/common/string.js +var string = { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/common/null.js +var nullTag = { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; + +// node_modules/yaml/browser/dist/schema/core/bool.js +var boolTag = { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str2) => new Scalar(str2[0] === "t" || str2[0] === "T"), + stringify({ source, value: value2 }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value2 === sv) + return source; + } + return value2 ? ctx.options.trueStr : ctx.options.falseStr; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyNumber.js +function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) { + if (typeof value2 === "bigint") + return String(value2); + const num2 = typeof value2 === "number" ? value2 : Number(value2); + if (!isFinite(num2)) + return isNaN(num2) ? ".nan" : num2 < 0 ? "-.inf" : ".inf"; + let n = Object.is(value2, -0) ? "-0" : JSON.stringify(value2); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} + +// node_modules/yaml/browser/dist/schema/core/float.js +var floatNaN = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2)); + const dot = str2.indexOf("."); + if (dot !== -1 && str2[str2.length - 1] === "0") + node.minFractionDigits = str2.length - dot - 1; + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/core/int.js +var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +var intResolve = (str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix); +function intStringify(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify(value2) && value2 >= 0) + return prefix + value2.toString(radix); + return stringifyNumber(node); +} +var intOct = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 8, opt2), + stringify: (node) => intStringify(node, 8, "0o") +}; +var int2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex = { + identify: (value2) => intIdentify(value2) && value2 >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str2, _onError, opt2) => intResolve(str2, 2, 16, opt2), + stringify: (node) => intStringify(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/core/schema.js +var schema = [ + map2, + seq, + string, + nullTag, + boolTag, + intOct, + int2, + intHex, + floatNaN, + floatExp, + float +]; + +// node_modules/yaml/browser/dist/schema/json/schema.js +function intIdentify2(value2) { + return typeof value2 === "bigint" || Number.isInteger(value2); +} +var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2); +var jsonScalars = [ + { + identify: (value2) => typeof value2 === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str2) => str2, + stringify: stringifyJSON + }, + { + identify: (value2) => value2 == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value2) => typeof value2 === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str2) => str2 === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), + stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2) + }, + { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str2) => parseFloat(str2), + stringify: stringifyJSON + } +]; +var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str2, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str2)}`); + return str2; + } +}; +var schema2 = [map2, seq].concat(jsonScalars, jsonError); + +// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +var binary = { + identify: (value2) => value2 instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str2 = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str2.length); + for (let i = 0; i < str2.length; ++i) + buffer[i] = str2.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) { + if (!value2) + return ""; + const buf = value2; + let str2; + if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str2 = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str2.length / lineWidth); + const lines2 = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines2[i] = str2.substr(o, lineWidth); + } + str2 = lines2.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep); + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value2; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value2 = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value2 = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value2, ctx)); + } + return pairs2; +} +var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value2; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value2 = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value2); + } + return map3; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } +}; +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +var omap = { + collection: "seq", + identify: (value2) => value2 instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +function boolStringify({ value: value2, source }, ctx) { + const boolObj = value2 ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value2 ? ctx.options.trueStr : ctx.options.falseStr; +} +var trueTag = { + identify: (value2) => value2 === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify +}; +var falseTag = { + identify: (value2) => value2 === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +var floatNaN2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber +}; +var floatExp2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str2) => parseFloat(str2.replace(/_/g, "")), + stringify(node) { + const num2 = Number(node.value); + return isFinite(num2) ? num2.toExponential() : stringifyNumber(node); + } +}; +var float2 = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str2) { + const node = new Scalar(parseFloat(str2.replace(/_/g, ""))); + const dot = str2.indexOf("."); + if (dot !== -1) { + const f = str2.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2); +function intResolve2(str2, offset, radix, { intAsBigInt }) { + const sign = str2[0]; + if (sign === "-" || sign === "+") + offset += 1; + str2 = str2.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str2 = `0b${str2}`; + break; + case 8: + str2 = `0o${str2}`; + break; + case 16: + str2 = `0x${str2}`; + break; + } + const n2 = BigInt(str2); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str2, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify2(node, radix, prefix) { + const { value: value2 } = node; + if (intIdentify3(value2)) { + const str2 = value2.toString(radix); + return value2 < 0 ? "-" + prefix + str2.substr(1) : prefix + str2; + } + return stringifyNumber(node); +} +var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 2, opt2), + stringify: (node) => intStringify2(node, 2, "0b") +}; +var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 1, 8, opt2), + stringify: (node) => intStringify2(node, 8, "0") +}; +var int3 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 0, 10, opt2), + stringify: stringifyNumber +}; +var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str2, _onError, opt2) => intResolve2(str2, 2, 16, opt2), + stringify: (node) => intStringify2(node, 16, "0x") +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value2) { + if (typeof value2 !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`); + const prev = findPair(this.items, key); + if (prev && !value2) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value2) { + this.items.push(new Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value2 of iterable) { + if (typeof replacer === "function") + value2 = replacer.call(iterable, value2, value2); + set2.items.push(createPair(value2, null, ctx)); + } + return set2; + } +}; +YAMLSet.tag = "tag:yaml.org,2002:set"; +var set = { + collection: "map", + identify: (value2) => value2 instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map3, onError) { + if (isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map3); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map3; + } +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +function parseSexagesimal(str2, asBigInt) { + const sign = str2[0]; + const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2; + const num2 = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0)); + return sign === "-" ? num2(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value: value2 } = node; + let num2 = (n) => n; + if (typeof value2 === "bigint") + num2 = (n) => BigInt(n); + else if (isNaN(value2) || !isFinite(value2)) + return stringifyNumber(node); + let sign = ""; + if (value2 < 0) { + sign = "-"; + value2 *= num2(-1); + } + const _60 = num2(60); + const parts = [value2 % _60]; + if (value2 < 60) { + parts.unshift(0); + } else { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2 % _60); + if (value2 >= 60) { + value2 = (value2 - parts[0]) / _60; + parts.unshift(value2); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +var intTime = { + identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str2, _onError, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), + stringify: stringifySexagesimal +}; +var floatTime = { + identify: (value2) => typeof value2 === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str2) => parseSexagesimal(str2, false), + stringify: stringifySexagesimal +}; +var timestamp = { + identify: (value2) => value2 instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str2) { + const match = str2.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; + +// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +var schema3 = [ + map2, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int3, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge3, + omap, + pairs, + set, + intTime, + floatTime, + timestamp +]; + +// node_modules/yaml/browser/dist/schema/tags.js +var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map2, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] +]); +var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int: int2, + intHex, + intOct, + intTime, + map: map2, + merge: merge3, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp +}; +var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge3, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge3); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); +} + +// node_modules/yaml/browser/dist/schema/Schema.js +var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +var Schema = class _Schema { + constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge4); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map2 }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy2.tags = this.tags.slice(); + return copy2; + } +}; + +// node_modules/yaml/browser/dist/stringify/stringifyDocument.js +function stringifyDocument(doc, options) { + const lines2 = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines2.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines2.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines2.length !== 1) + lines2.unshift(""); + const cs = commentString(doc.commentBefore); + lines2.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines2.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines2.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines2[lines2.length - 1] === "---") { + lines2[lines2.length - 1] = `--- ${body}`; + } else + lines2.push(body); + } else { + lines2.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines2.push("..."); + lines2.push(indentComment(cs, "")); + } else { + lines2.push(`... ${cs}`); + } + } else { + lines2.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines2[lines2.length - 1] !== "") + lines2.push(""); + lines2.push(indentComment(commentString(dc), "")); + } + } + return lines2.join("\n") + "\n"; +} + +// node_modules/yaml/browser/dist/doc/Document.js +var Document = class _Document { + constructor(value2, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt2 = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt2; + let { version } = opt2; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy2 = Object.create(_Document.prototype, { + [NODE_TYPE]: { value: DOC } + }); + copy2.commentBefore = this.commentBefore; + copy2.comment = this.comment; + copy2.errors = this.errors.slice(); + copy2.warnings = this.warnings.slice(); + copy2.options = Object.assign({}, this.options); + if (this.directives) + copy2.directives = this.directives.clone(); + copy2.schema = this.schema.clone(); + copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents; + if (this.range) + copy2.range = this.range.slice(); + return copy2; + } + /** Adds a value to the document. */ + add(value2) { + if (assertCollection(this.contents)) + this.contents.add(value2); + } + /** Adds a value to the document. */ + addIn(path, value2) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value2); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value2, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value2 = replacer.call({ "": value2 }, "", value2); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode2(value2, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value2, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value2, null, options); + return new Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value2) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value2); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value2); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value2) { + if (isEmptyPath(path)) { + this.contents = value2; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value2); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value2); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt2; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt2 = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt2 = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt2 = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt2) + this.schema = new Schema(Object.assign(opt2, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} + +// node_modules/yaml/browser/dist/errors.js +var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +}; +var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +}; +var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +}; +var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer2} +`; + } +}; + +// node_modules/yaml/browser/dist/compose/resolve-props.js +function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} + +// node_modules/yaml/browser/dist/compose/util-contains-newline.js +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} + +// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } +} + +// node_modules/yaml/browser/dist/compose/util-map-includes.js +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} + +// node_modules/yaml/browser/dist/compose/resolve-block-map.js +var startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value: value2 } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += "\n" + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value2?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value2, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-seq.js +function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value: value2 } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value2, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value2) { + if (value2?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value2, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} + +// node_modules/yaml/browser/dist/compose/resolve-end.js +function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +var blockMsg = "Block collections are not allowed within flow collections"; +var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value: value2 } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value2) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value2, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value2) { + if ("source" in value2 && value2.source?.[0] === ":") + onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value2)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map3 = coll; + if (mapIncludes(ctx, map3.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} + +// node_modules/yaml/browser/dist/compose/compose-collection.js +function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} + +// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines2 = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines2.length; + for (let i = lines2.length - 1; i >= 0; --i) { + const content = lines2[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value3 = header.chomp === "+" && lines2.length > 0 ? "\n".repeat(Math.max(1, lines2.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value3, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines2[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines2.length - 1; i >= chompStart; --i) { + if (lines2[i][0].length > trimIndent) + chompStart = i + 1; + } + let value2 = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value2 += lines2[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines2[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value2 += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value2 += "\n"; + else + sep = "\n"; + } else { + value2 += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines2.length; ++i) + value2 += "\n" + lines2[i][0].slice(trimIndent); + if (value2[value2.length - 1] !== "\n") + value2 += "\n"; + break; + default: + value2 += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines2 = [line0]; + for (let i = 1; i < split.length; i += 2) + lines2.push([split[i], split[i + 1]]); + return lines2; +} + +// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value2; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value2 = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value2 = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value2 = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, strict, onError); + return { + value: value2, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} + +// node_modules/yaml/browser/dist/compose/compose-scalar.js +function composeScalar(ctx, token, tagToken, onError) { + const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value2, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value2); + } + scalar.range = range; + scalar.source = value2; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema4, value2, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value2)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; +} +function findScalarTagByTest({ atKey, directives, schema: schema4 }, value2, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} + +// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} + +// node_modules/yaml/browser/dist/compose/compose-node.js +var CN = { composeNode, composeEmptyNode }; +function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} + +// node_modules/yaml/browser/dist/compose/compose-doc.js +function composeDoc(options, directives, { offset, start, value: value2, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value2 ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} + +// node_modules/yaml/browser/dist/compose/composer.js +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +}; + +// node_modules/yaml/browser/dist/parse/cst.js +var cst_exports = {}; +__export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 +}); + +// node_modules/yaml/browser/dist/parse/cst-scalar.js +function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value2, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value: value2 }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value2, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value: value2 }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} + +// node_modules/yaml/browser/dist/parse/cst-stringify.js +var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value: value2 }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value2) + res += stringifyToken(value2); + return res; +} + +// node_modules/yaml/browser/dist/parse/cst-visit.js +var BREAK2 = /* @__PURE__ */ Symbol("break visit"); +var SKIP2 = /* @__PURE__ */ Symbol("skip children"); +var REMOVE2 = /* @__PURE__ */ Symbol("remove item"); +function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); +} +visit2.BREAK = BREAK2; +visit2.SKIP = SKIP2; +visit2.REMOVE = REMOVE2; +visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} + +// node_modules/yaml/browser/dist/parse/cst.js +var BOM = "\uFEFF"; +var DOCUMENT = ""; +var FLOW_END = ""; +var SCALAR2 = ""; +var isCollection2 = (token) => !!token && "items" in token; +var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} + +// node_modules/yaml/browser/dist/parse/lexer.js +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +var hexDigits = new Set("0123456789ABCDEFabcdef"); +var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +var flowIndicatorChars = new Set(",[]{}"); +var invalidAnchorChars = new Set(" ,[]{}\n\r "); +var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +}; + +// node_modules/yaml/browser/dist/parse/line-counter.js +var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +}; + +// node_modules/yaml/browser/dist/parse/parser.js +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +}; + +// node_modules/yaml/browser/dist/public-api.js +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; +} +function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify3(value2, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value2 === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value2) && !_replacer) + return value2.toString(options); + return new Document(value2, _replacer, options).toString(options); +} + +// node_modules/yaml/browser/index.js +var browser_default = dist_exports4; + // node_modules/@earendil-works/pi-durable/dist/tools/index.js var tools_exports = {}; __export(tools_exports, { @@ -29067,7 +35707,7 @@ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, ne const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines2 = current.lines || splitLines(current.value); + const current = diff[i], lines2 = current.lines || splitLines2(current.value); current.lines = lines2; if (current.added || current.removed) { if (!oldRangeStart) { @@ -29192,7 +35832,7 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader } })); } } -function splitLines(text) { +function splitLines2(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { @@ -30103,8 +36743,8 @@ function createCodingTools(options = {}) { var CodingTools = createCodingTools(); // node_modules/@earendil-works/pi-ai/dist/index.js -var dist_exports4 = {}; -__export(dist_exports4, { +var dist_exports5 = {}; +__export(dist_exports5, { AI_TELEMETRY_SCHEMA: () => AI_TELEMETRY_SCHEMA, AssistantMessageEventStream: () => AssistantMessageEventStream, DEFAULT_MAX_AGENT_RETRY_DELAY_MS: () => DEFAULT_MAX_AGENT_RETRY_DELAY_MS, @@ -30306,11 +36946,11 @@ async function emit(tx, event, data) { if (feed.length > EVENT_FEED_SIZE) feed.splice(0, feed.length - EVENT_FEED_SIZE); return emitted; } -async function scan(tx, log, after, visit) { +async function scan(tx, log, after, visit3) { let cursor; do { const page3 = await tx.scanEntries({ conversationId: log, minEntryId: after + 1, order: "ascending" }, 256, cursor); - for (const entry2 of page3.items) if (visit(entry2)) return; + for (const entry2 of page3.items) if (visit3(entry2)) return; cursor = page3.next; } while (cursor); } @@ -30527,7 +37167,7 @@ async function git(cwd, ...args) { return result.stdout.trim(); } function registerModules() { - const modules = { "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports4, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; + const modules = { "yaml": browser_exports, "@earendil-works/sausage-events": events_exports, "@earendil-works/pi-schema": dist_exports, "@earendil-works/pi-durable": dist_exports3, "@earendil-works/pi-durable/tools": tools_exports, "@earendil-works/pi-ai": dist_exports5, "@earendil-works/pi-ai/models": models_exports, "@earendil-works/chord": dist_exports2, "@earendil-works/chord/context": context_exports }; globalThis.__sausage = { modules }; ops2.op_modules(Object.fromEntries(Object.entries(modules).map(([name, value2]) => [name, Object.keys(value2)]))); } @@ -30756,7 +37396,12 @@ Last good: ${fallback}` : failed; if (active) await enqueue2(); } })(); - return { reload: enqueue2, state: () => ({ ...state }), async invoke(name, key, args, signal, conversationId) { + return { reload: enqueue2, state: () => ({ ...state }), async standing() { + if (!providers.has("models") || !providers.has("subagents")) return void 0; + const { standing: name } = await providers.get("models").discover(repo); + const conversationId = await providers.get("subagents").standing(name, context); + return { name, conversationId }; + }, async invoke(name, key, args, signal, conversationId) { const facet = facets.find((f) => f.extension.name === name); const action = facet?.actions?.[key]; if (!action) throw Object.assign(new Error("Unknown user action"), { status: 404 }); @@ -30858,8 +37503,8 @@ function createSqliteSchema(prefix) { var DEFAULT_SQLITE_SCHEMA = createSqliteSchema(); // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/migrations.js -function createSqliteMigrations(schema) { - const { tables, indexes } = schema; +function createSqliteMigrations(schema4) { + const { tables, indexes } = schema4; const initialSchema = [ `CREATE TABLE ${tables.durableMetadata} ( singleton INTEGER PRIMARY KEY CHECK (singleton = 1), @@ -30965,8 +37610,8 @@ function createSqliteMigrations(schema) { } var SQLITE_MIGRATIONS = createSqliteMigrations(DEFAULT_SQLITE_SCHEMA); var CURRENT_SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.at(-1)?.version ?? 0; -async function applySqliteMigrationsForSchema(database, schema, migrations = createSqliteMigrations(schema)) { - await applySqliteMigrations(database, migrations, { table: schema.tables.durableSchema }); +async function applySqliteMigrationsForSchema(database, schema4, migrations = createSqliteMigrations(schema4)) { + await applySqliteMigrations(database, migrations, { table: schema4.tables.durableSchema }); } // node_modules/@earendil-works/pi-durable/dist/storage/sqlite/storage.js @@ -31057,20 +37702,20 @@ var SqliteStorage = class _SqliteStorage { closing; admittedReads = 0; readsDrained; - constructor(db, schema, nextId) { + constructor(db, schema4, nextId) { this.db = db; - this.schema = schema; + this.schema = schema4; this.nextId = nextId; } /** Initialize storage over an owned SQLite database facade. */ static async open(db, options = {}) { try { - const schema = createSqliteSchema(options.prefix); - await applySqliteMigrationsForSchema(db, schema); - const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`); + const schema4 = createSqliteSchema(options.prefix); + await applySqliteMigrationsForSchema(db, schema4); + const metadata = await db.get(`SELECT next_id, next_seq FROM ${schema4.tables.durableMetadata} WHERE singleton = 1`); if (metadata === void 0) throw new Error("Durable SQLite metadata is missing"); - return new _SqliteStorage(db, schema, Number(metadata.next_id)); + return new _SqliteStorage(db, schema4, Number(metadata.next_id)); } catch (error) { try { await db.close(); @@ -31106,9 +37751,9 @@ var SqliteStorage = class _SqliteStorage { refused = { error }; break; } - const seq = seqFromNumber(next++); - await this.applyBatch(transaction, writes, documentActions, seq); - seqs.push(seq); + const seq2 = seqFromNumber(next++); + await this.applyBatch(transaction, writes, documentActions, seq2); + seqs.push(seq2); candidateNextId = Math.max(candidateNextId, this.candidateNextId(writes)); } if (seqs.length > 0) { @@ -31116,8 +37761,8 @@ var SqliteStorage = class _SqliteStorage { } }); this.nextId = Math.max(this.nextId, candidateNextId); - for (const [index, seq] of seqs.entries()) - receive(index, seq); + for (const [index, seq2] of seqs.entries()) + receive(index, seq2); return refused === void 0 ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error }; } async readMetadata(executor) { @@ -31135,10 +37780,10 @@ var SqliteStorage = class _SqliteStorage { await this.checkDocumentActions(executor, documentActions); await this.resolveCopies(executor, documentActions); } - async applyBatch(executor, writes, documentActions, seq) { + async applyBatch(executor, writes, documentActions, seq2) { for (const write of writes) - await this.applyTableWrite(executor, write, seq); - await this.applyDocumentActions(executor, documentActions, seq); + await this.applyTableWrite(executor, write, seq2); + await this.applyDocumentActions(executor, documentActions, seq2); } async mintId() { this.assertOpen(); @@ -31574,7 +38219,7 @@ var SqliteStorage = class _SqliteStorage { LIMIT 1`, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue))?.id; return id === void 0 ? void 0 : idFromNumber(id); } - async applyTableWrite(executor, write, seq) { + async applyTableWrite(executor, write, seq2) { switch (write.type) { case "conversation": await this.claimId(executor, write.value.id, "conversation"); @@ -31582,7 +38227,7 @@ var SqliteStorage = class _SqliteStorage { break; case "entry": await this.claimId(executor, write.value.id, "entry"); - await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq, encodeJson(write.value)); + await executor.run(`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`, write.value.id, write.value.conversationId, write.value.head ?? null, seq2, encodeJson(write.value)); break; case "task": await this.claimId(executor, write.value.id, "task"); @@ -31627,21 +38272,21 @@ var SqliteStorage = class _SqliteStorage { } } } - async applyDocumentActions(executor, actions, seq) { + async applyDocumentActions(executor, actions, seq2) { for (const [id, action] of actions) { const content = action.content; let record2; if (action.create !== void 0) { record2 = { ...action.create, - createdAt: seq, - ...action.retire ? { retiredAt: seq } : {} + createdAt: seq2, + ...action.retire ? { retiredAt: seq2 } : {} }; const parts = addressParts(record2); await this.claimId(executor, id, "document"); await executor.run(`INSERT INTO ${this.schema.tables.documents} (id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq, action.retire ? seq : null, encodeJson(record2)); + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, seq2, action.retire ? seq2 : null, encodeJson(record2)); } else { const row = await executor.get(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id); record2 = parseJson(row.record); @@ -31651,12 +38296,12 @@ var SqliteStorage = class _SqliteStorage { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); } const encodedContent = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops); - await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq, content.kind, content.version, encodedContent); + await executor.run(`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`, id, seq2, content.kind, content.version, encodedContent); } if (action.retire) { if (action.create === void 0) { - record2 = { ...record2, retiredAt: seq }; - await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq, encodeJson(record2), id); + record2 = { ...record2, retiredAt: seq2 }; + await executor.run(`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`, seq2, encodeJson(record2), id); } if (isCurrentOnly2(record2)) { await executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id); diff --git a/host/src/harness/config.rs b/host/src/harness/config.rs new file mode 100644 index 0000000..0f7910a --- /dev/null +++ b/host/src/harness/config.rs @@ -0,0 +1,44 @@ +//! Fresh reads of the user-owned world configuration. Listener edits apply at host startup. +use sausage_vfs::{Layer, Open}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +pub const PATH: &str = "/etc/sausage/config.yaml"; +#[derive(Default, Deserialize, Serialize)] +#[serde(default)] +pub struct Proxy { + pub base_url: String, + pub api_key: String, +} +#[derive(Deserialize)] +pub struct Listener { + pub address: std::net::SocketAddr, + pub origin: String, +} +impl Default for Listener { + fn default() -> Self { + Self { + address: "127.0.0.1:8090".parse().unwrap(), + origin: "http://localhost:8090".into(), + } + } +} +#[derive(Default, Deserialize)] +#[serde(default)] +pub struct Config { + pub proxy: Proxy, + pub listener: Listener, +} +impl Config { + pub async fn read(root: &Arc) -> anyhow::Result { + let file = match root.open(PATH, Open::default()).await { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(Self::default()); + } + Err(error) => return Err(error.into()), + }; + serde_yaml_ng::from_slice(&file.read(0, 16 * 1024 * 1024).await?) + .map_err(|error| anyhow::anyhow!("Cannot read {PATH}: {error}")) + } +} diff --git a/host/src/harness/credentials.rs b/host/src/harness/credentials.rs index 6799285..acd00e8 100644 --- a/host/src/harness/credentials.rs +++ b/host/src/harness/credentials.rs @@ -66,97 +66,18 @@ pub(super) fn op_credential_requests(state: &mut OpState) -> Result anyhow::Result> { - use crate::cred::{ - items::{Field, Item}, - types::{Caller, FieldType}, - }; - let caller = Caller { - pid: 0, - program: "host".into(), - conversations: vec![], - }; - let item = cred - .item_list()? - .into_iter() - .find(|item| item.name == "llm-proxy"); - let item = match item { - Some(item) => item, - None => { - let (Ok(base), Ok(key)) = ( - std::env::var("PI_PROXY_BASE_URL"), - std::env::var("PI_PROXY_API_KEY"), - ) else { - return Ok(None); - }; - let mut store = cred.access()?; - let master = store.master.clone(); - let tx = store - .db - .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - let mut item = crate::cred::items::insert_new( - &tx, - Item { - id: String::new(), - name: "llm-proxy".into(), - version: 0, - free_use: false, - rules: vec![], - validate_js: None, - transform_js: "export default (ctx) => ctx.request".into(), - fields: vec![ - Field { - field_id: String::new(), - name: "base_url".into(), - public: true, - value: Some(base), - needs_value: false, - field_type: FieldType::Text, - key_type: None, - }, - Field { - field_id: String::new(), - name: "api_key".into(), - public: false, - value: None, - needs_value: true, - field_type: FieldType::Text, - key_type: None, - }, - ], - }, - &caller, - Some("host bootstrap"), - )?; - let field = &item - .fields - .iter() - .find(|f| f.name == "api_key") - .unwrap() - .field_id; - let sealed = - crate::cred::seal::seal(&master, &format!("{}|{field}", item.id), key.as_bytes())?; - tx.execute( - "INSERT INTO fields VALUES(?1,?2,?3)", - rusqlite::params![item.id, field, sealed], - )?; - item.fields - .iter_mut() - .find(|f| f.name == "api_key") - .unwrap() - .needs_value = false; - crate::cred::items::save(&tx, &item)?; - tx.commit()?; - item - } - }; - Ok(Some(cred.credential(&item, true)?)) -} - #[op2] #[serde] -pub(super) fn op_model_proxy(state: &mut OpState) -> Result { - proxy(state.borrow::>()) - .map(|v| v.unwrap_or(Value::Null)) - .map_err(|_| JsErrorBox::generic("Cannot read llm-proxy credential")) +pub(super) async fn op_model_proxy( + state: Rc>, +) -> Result { + let root = state + .borrow() + .borrow::() + .root + .clone(); + let config = super::config::Config::read(&root) + .await + .map_err(|error| JsErrorBox::generic(error.to_string()))?; + serde_json::to_value(config.proxy).map_err(|error| JsErrorBox::generic(error.to_string())) } diff --git a/host/src/harness/loader.rs b/host/src/harness/loader.rs index c24bfd1..8d75a6d 100644 --- a/host/src/harness/loader.rs +++ b/host/src/harness/loader.rs @@ -81,7 +81,7 @@ impl ModuleLoader for Loader { referrer: &str, _: ResolutionKind, ) -> Result { - if specifier.starts_with("@earendil-works/") { + if specifier == "yaml" || specifier.starts_with("@earendil-works/") { return ModuleSpecifier::parse(&format!("sausage:{specifier}")) .map_err(|e| JsErrorBox::generic(e.to_string())); } diff --git a/host/src/harness/mod.rs b/host/src/harness/mod.rs index 11c0169..5ba647c 100644 --- a/host/src/harness/mod.rs +++ b/host/src/harness/mod.rs @@ -1,4 +1,5 @@ //! Durable V8 harness, host-side SQLite storage, and world tool operations. +pub mod config; mod credentials; mod environment; mod http; @@ -157,7 +158,7 @@ pub async fn run_module_with_input( receiver: input::Receiver, source: &str, ) -> anyhow::Result<()> { - let proxy = credentials::proxy(&cred)?; + let proxy = serde_json::to_value(config::Config::read(&world.root).await?.proxy)?; let loader = std::rc::Rc::new(loader::Loader { root: world.root.clone(), modules: Default::default(), @@ -239,10 +240,7 @@ pub async fn run_module_with_input( .await; result.map_err(|error| { let mut text = error.to_string(); - if let Some(key) = proxy - .as_ref() - .and_then(|v| v.get("api_key")) - .and_then(Value::as_str) + if let Some(key) = proxy.get("api_key").and_then(Value::as_str) && !key.is_empty() { text = text.replace(key, "[redacted]"); diff --git a/host/src/main.rs b/host/src/main.rs index cda1166..a889bd8 100644 --- a/host/src/main.rs +++ b/host/src/main.rs @@ -14,14 +14,14 @@ struct Cli { #[derive(Subcommand)] enum Command { - /// Start a world: the harness, its services and a console. - Run { + /// Create a world with default tools and /etc/sausage/config.yaml. + Init { world: PathBuf, #[arg(long)] userland: Option, - #[command(flatten)] - api: sausage::api::Options, }, + /// Start a world: the harness, its services and a console. + Run { world: PathBuf }, /// Run a shell in a world. With `-c`, run one command and exit with its status. Sh { world: PathBuf, @@ -39,14 +39,33 @@ async fn main() -> anyhow::Result<()> { sausage::process::configure_cache(cache)?; } match cli.command { - Command::Run { - world, - userland, - api, - } => { - let bundle = - userland.or_else(|| std::env::var_os("SAUSAGE_USERLAND").map(PathBuf::from)); - sausage::api::run_with_userland(&world, bundle.as_deref(), api).await + Command::Init { world, userland } => { + let bundle = userland + .or_else(|| std::env::var_os("SAUSAGE_USERLAND").map(PathBuf::from)) + .ok_or_else(|| { + anyhow::anyhow!( + "Default tools unavailable. Set SAUSAGE_USERLAND or pass --userland." + ) + })?; + sausage::world::World::init(&world, &bundle).await?; + Ok(()) + } + Command::Run { world } => { + anyhow::ensure!( + world.join("world").is_dir(), + "No world at {}. Run sausage init {} first.", + world.display(), + world.display() + ); + let opened = sausage::world::World::open(&world)?; + let config = sausage::harness::config::Config::read(&opened.root).await?; + let origin = url::Url::parse(&config.listener.origin)?; + let api = sausage::api::Options { + api_listen: config.listener.address, + api_rp_id: origin.host_str().unwrap_or("localhost").into(), + api_origin: config.listener.origin, + }; + sausage::api::run_with_userland(&world, None, api).await } Command::Sh { world, diff --git a/host/src/world.rs b/host/src/world.rs index 6878d3d..4f9cd34 100644 --- a/host/src/world.rs +++ b/host/src/world.rs @@ -3,7 +3,7 @@ //! Layout of a world directory: //! - `world/`: the virtual root `/` that every guest sees. Agents change everything in it. //! - `host/`: host state outside the sandbox (harness storage, later the vault). No guest sees it. -use sausage_vfs::{Device, Generated, Host, Layer, Memory, Mounts, Process}; +use sausage_vfs::{Device, Generated, Host, Layer, Memory, Mounts, Open, Process}; use std::{ os::unix::fs::PermissionsExt, path::{Path, PathBuf}, @@ -43,6 +43,75 @@ fn copy_tree(source: &Path, destination: &Path) -> std::io::Result<()> { } impl World { + /// Initialize a fresh world and commit its plain bundled source on main. + pub async fn init(dir: &Path, bundle: &Path) -> anyhow::Result { + anyhow::ensure!( + !dir.join("world").exists(), + "World already exists: {}", + dir.display() + ); + let world = Self::open_with_userland(dir, Some(bundle))?; + let path = crate::harness::config::PATH; + let config = world.root.open(path, Open::default()).await?; + let mut text = String::from_utf8(config.read(0, 16 * 1024 * 1024).await?)?; + for (field, variable) in [ + ("base_url", "PI_PROXY_BASE_URL"), + ("api_key", "PI_PROXY_API_KEY"), + ] { + if let Ok(value) = std::env::var(variable) { + text = text.replace( + &format!("{field}: \"\""), + &format!("{field}: {}", serde_json::to_string(&value)?), + ); + } + } + let file = world + .root + .open( + path, + Open { + write: true, + truncate: true, + ..Default::default() + }, + ) + .await?; + file.write(0, text.into_bytes()).await?; + let exec = crate::process::exec(Self { + root: world.root.clone(), + host_dir: world.host_dir.clone(), + processes: world.processes.clone(), + })?; + for args in [ + vec!["init", "-b", "main"], + vec!["add", "."], + vec!["commit", "--no-gpg-sign", "-m", "Initial world source"], + ] { + let argv = [ + vec!["/bin/git.wasm".to_owned()], + args.into_iter().map(str::to_owned).collect(), + ] + .concat(); + let mut output = Vec::new(); + let code = exec + .exec( + crate::exec::Command::Argv(argv), + crate::exec::Options { + cwd: "/src/sausage".into(), + ..Default::default() + }, + &mut |_, bytes| output.extend_from_slice(bytes), + ) + .await?; + anyhow::ensure!( + code == 0, + "Cannot initialize source repository: {}", + String::from_utf8_lossy(&output) + ); + } + Ok(world) + } + /// Open (and create if missing) the world directory `dir`, including `/proc` and `/run` mounts. pub fn open(dir: &Path) -> anyhow::Result { Self::open_with_userland(dir, None) diff --git a/host/tests/it/api_listener.rs b/host/tests/it/api_listener.rs index 26b9077..40d991f 100644 --- a/host/tests/it/api_listener.rs +++ b/host/tests/it/api_listener.rs @@ -1,4 +1,4 @@ -//! Native HTTP smoke test for host pages and the listener's CLI options. +//! Host pages remain reachable. World config replaces listener flags on the CLI. use anyhow::Result; use sausage::{ api::{Listener, Options}, @@ -44,14 +44,16 @@ fn listener_serves_host_pages() -> Result<()> { .output()?; assert!(help.status.success()); let help = std::str::from_utf8(&help.stdout)?; - for option in [ - "--api-listen", - "127.0.0.1:8090", - "--api-rp-id", - "--api-origin", - "http://localhost:8090", - ] { - assert!(help.contains(option)); + for option in ["--api-listen", "--api-rp-id", "--api-origin"] { + assert!(!help.contains(option)); } + let missing = dir.path().join("missing-world"); + let run = std::process::Command::new(env!("CARGO_BIN_EXE_sausage")) + .arg("run") + .arg(&missing) + .output()?; + assert!(!run.status.success()); + assert!(std::str::from_utf8(&run.stderr)?.contains("sausage init")); + assert!(!missing.join("world").exists()); Ok(()) } diff --git a/host/tests/it/automations.rs b/host/tests/it/automations.rs index d08c722..8844999 100644 --- a/host/tests/it/automations.rs +++ b/host/tests/it/automations.rs @@ -79,10 +79,12 @@ fn setup(directory: &Path) -> Result<()> { &Path::new(env!("CARGO_MANIFEST_DIR")).join("../extensions"), &repo.join("extensions"), )?; - std::fs::create_dir_all(repo.join("agents"))?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"}}"#, + crate::common::write_config( + directory, + "standing", + serde_json::json!([ + {"name":"standing","description":"Primary","model":"faux/faux-1","prompt":"Primary agent"} + ]), )?; ensure!( Command::new("git") diff --git a/host/tests/it/common.rs b/host/tests/it/common.rs index 1d11577..bcded8d 100644 --- a/host/tests/it/common.rs +++ b/host/tests/it/common.rs @@ -8,6 +8,22 @@ use std::{ }; pub static BUILD: Mutex<()> = Mutex::new(()); +/// Keep the real shared prompt in every roster fixture, with an ephemeral approval port. +pub fn write_config(dir: &Path, standing: &str, roster: serde_json::Value) -> anyhow::Result<()> { + let mut config: serde_json::Value = + serde_yaml_ng::from_str(include_str!("../../../config/config.yaml"))?; + config["standing"] = serde_json::json!(standing); + config["roster"] = roster; + config["listener"]["address"] = serde_json::json!("127.0.0.1:0"); + let folder = dir.join("world/etc/sausage"); + std::fs::create_dir_all(&folder)?; + std::fs::write( + folder.join("config.yaml"), + serde_yaml_ng::to_string(&config)?, + )?; + Ok(()) +} + pub fn copy_tree(source: &Path, destination: &Path) -> anyhow::Result<()> { std::fs::create_dir_all(destination)?; for entry in std::fs::read_dir(source)? { @@ -39,7 +55,7 @@ pub fn bundle_key(repo: &Path) -> anyhow::Result { "host", "vfs", "userland", - "agents", + "config", "skills", "extensions", "Cargo.toml", diff --git a/host/tests/it/core_ext.rs b/host/tests/it/core_ext.rs index 024b061..4b80df1 100644 --- a/host/tests/it/core_ext.rs +++ b/host/tests/it/core_ext.rs @@ -44,6 +44,70 @@ fn write(root: &Path, path: &str, text: &str) -> anyhow::Result<()> { std::fs::write(path, text)?; Ok(()) } +#[tokio::test(flavor = "current_thread")] +async fn init_seeds_config_tools_and_one_source_commit() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let bundle = dir.path().join("bundle"); + let target = crate::common::build_git(); + std::fs::create_dir_all(bundle.join("bin"))?; + std::fs::copy( + target.join("wasm32-wasip2/release/git.wasm"), + bundle.join("bin/git.wasm"), + )?; + write(&bundle, "src/sausage/README.md", "World source")?; + write( + &bundle, + "etc/sausage/config.yaml", + include_str!("../../../config/config.yaml"), + )?; + let destination = dir.path().join("new-world"); + let initialized = std::process::Command::new(env!("CARGO_BIN_EXE_sausage")) + .arg("init") + .arg(&destination) + .arg("--userland") + .arg(&bundle) + .env("PI_PROXY_BASE_URL", "https://proxy.test") + .env("PI_PROXY_API_KEY", "fixture-key") + .stdin(std::process::Stdio::null()) + .output()?; + assert!( + initialized.status.success(), + "{}", + String::from_utf8_lossy(&initialized.stderr) + ); + let world = World::open(&destination)?; + assert!(destination.join("world/bin/git").exists()); + let config = sausage::harness::config::Config::read(&world.root).await?; + assert_eq!(config.listener.origin, "http://localhost:8090"); + assert_eq!(config.proxy.base_url, "https://proxy.test"); + assert_eq!(config.proxy.api_key, "fixture-key"); + let source = destination.join("world/src/sausage"); + for (args, expected) in [ + (vec!["symbolic-ref", "HEAD"], "refs/heads/main"), + (vec!["rev-list", "--count", "HEAD"], "1"), + ] { + let result = std::process::Command::new("git") + .args(args) + .current_dir(&source) + .output()?; + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + assert_eq!(String::from_utf8(result.stdout)?.trim(), expected); + } + assert!( + World::init(&destination, &bundle) + .await + .err() + .unwrap() + .to_string() + .contains("already exists") + ); + Ok(()) +} + #[tokio::test(flavor = "current_thread")] async fn core_extensions() -> anyhow::Result<()> { let repo = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); @@ -66,14 +130,9 @@ async fn core_extensions() -> anyhow::Result<()> { )?; } write( - &source, - "agents/worker.md", - "---\nname: worker\ndescription: Worker\nfamily: fast\ntools: [read]\n---\nWorker body", - )?; - write( - &source, - "agents/models.json", - r#"{"default":{"model":"faux/faux-1"},"fast":{"model":"faux/faux-1","thinking":"low"}}"#, + &disk, + "etc/sausage/config.yaml", + include_str!("../../../config/config.yaml"), )?; write( &source, @@ -93,11 +152,6 @@ export default host=>{host.implement({name:'models.pin'},{pin:async()=>globalThi write(&disk, "project/.git/HEAD", "ref: refs/heads/main")?; write(&disk, "project/AGENTS.md", "Root instructions")?; write(&disk, "project/sub/AGENTS.md", "Nested instructions")?; - write( - &disk, - "project/.sausage/agents/worker.md", - "---\nname: worker\naddTools: [write]\n---\nProject body", - )?; write( &disk, "project/.sausage/skills/project/SKILL.md", diff --git a/host/tests/it/dream.rs b/host/tests/it/dream.rs index 0e2d147..b3b341d 100644 --- a/host/tests/it/dream.rs +++ b/host/tests/it/dream.rs @@ -50,33 +50,23 @@ fn prepare(dir: &Path) -> anyhow::Result<()> { repo.join("extensions/probe/server.ts"), "export default host => { globalThis.dreamHost=host; globalThis.dreamService=host.need({name:'dream'}); globalThis.dreamSubagents=host.need({name:'subagents'}); globalThis.dreamAutomations=host.need({name:'automations'}); return {name:'probe'}; }", )?; - std::fs::create_dir_all(repo.join("agents"))?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"},"fast":{"model":"faux/faux-1"}}"#, - )?; - for role in ["ultimate", "coordinator", "worker", "reviewer"] { - let denial = if role == "worker" || role == "reviewer" { - "denyTools: [subagent]\n" - } else { - "" - }; - std::fs::write( - repo.join(format!("agents/{role}.md")), - format!( - "---\nname: {role}\ndescription: P3 {role}\nisolate: none\n{denial}{}---\nP3 role:{role}\n", - if role == "ultimate" { - "resident: true\n" - } else { - "" - } - ), - )?; - } - std::fs::copy( - source.join("agents/dream-pass.md"), - repo.join("agents/dream-pass.md"), - )?; + let mut roster: Vec = ["standing", "coordinator", "worker", "reviewer"].into_iter().map(|role| serde_json::json!({ + "name":role, "description":format!("P3 {role}"), "model":"faux/faux-1", + "isolate":"none", "resident":role == "standing", "prompt":format!("P3 role:{role}"), + "denyTools":if role == "worker" || role == "reviewer" {vec!["subagent"]} else {vec![]} + })).collect(); + let defaults: serde_json::Value = + serde_yaml_ng::from_str(include_str!("../../../config/config.yaml"))?; + let mut pass = defaults["roster"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["name"] == "dream-pass") + .unwrap() + .clone(); + pass["model"] = serde_json::json!("faux/faux-1"); + roster.push(pass); + crate::common::write_config(dir, "standing", serde_json::json!(roster))?; let demo = disk.join("src/demo"); std::fs::create_dir_all(&demo)?; std::fs::write(demo.join("README.md"), "P3 demo\n")?; diff --git a/host/tests/it/durable.rs b/host/tests/it/durable.rs index 47044c9..b9fc795 100644 --- a/host/tests/it/durable.rs +++ b/host/tests/it/durable.rs @@ -146,7 +146,7 @@ async fn proxy_child() -> anyhow::Result<()> { }; let dir = std::path::Path::new(&dir); let source = format!( - "globalThis.proxyOnly = true; const proxy = Deno.core.ops.op_model_proxy(); if (proxy.base_url !== 'https://proxy.invalid' || proxy.api_key !== 'faux-private-token') throw new Error('Wrong proxy item');\n{}", + "globalThis.proxyOnly = true; const proxy = await Deno.core.ops.op_model_proxy(); if (proxy.base_url !== 'https://proxy.invalid' || proxy.api_key !== 'faux-private-token') throw new Error('Wrong proxy config');\n{}", include_str!("../../js/durable-test-bundle.js") ); run_module( @@ -158,7 +158,7 @@ async fn proxy_child() -> anyhow::Result<()> { let error = run_module( World::open(dir)?, sausage::process::exec(World::open(dir)?)?, - "throw new Error(Deno.core.ops.op_model_proxy().api_key)", + "throw new Error((await Deno.core.ops.op_model_proxy()).api_key)", ) .await .unwrap_err(); @@ -168,8 +168,14 @@ async fn proxy_child() -> anyhow::Result<()> { } #[test] -fn proxy_bootstrap_once() -> anyhow::Result<()> { +fn proxy_config_ignores_environment() -> anyhow::Result<()> { let dir = std::env::temp_dir().join(format!("sausage-durable-proxy-{}", std::process::id())); + let settings = dir.join("world/etc/sausage"); + std::fs::create_dir_all(&settings)?; + std::fs::write( + settings.join("config.yaml"), + "proxy:\n base_url: https://proxy.invalid\n api_key: faux-private-token\n", + )?; for start in 0..2 { let status = std::process::Command::new(std::env::current_exe()?) .args(["--exact", "durable::proxy_child", "--nocapture"]) @@ -199,7 +205,7 @@ fn proxy_bootstrap_once() -> anyhow::Result<()> { .iter() .filter(|i| i.name == "llm-proxy") .count(), - 1 + 0 ); for file in [ "host/cred.sqlite", diff --git a/host/tests/it/goal_questions.rs b/host/tests/it/goal_questions.rs index 1356a79..75b1ae1 100644 --- a/host/tests/it/goal_questions.rs +++ b/host/tests/it/goal_questions.rs @@ -26,21 +26,37 @@ fn prepare(dir: &Path) -> anyhow::Result<()> { repo.join("extensions/probe/server.ts"), "export default host => { globalThis.testHost = host; globalThis.subagentService = host.need({name:'subagents'}); globalThis.messageService = host.need({name:'messages'}); globalThis.lineageService = host.need({name:'lineage'}); host.implement({name:'conversations'}, {summaryModel: async () => globalThis.summaryRef, concludedIn: async () => new Set(), generatedTitle: async () => {}, setStanding: async () => {}, setAutomaticSummaries: async () => {}}); return {name:'probe'}; }", )?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"}}"#, - )?; - std::fs::write( - repo.join("agents/scout.md"), - "---\nname: scout\ndescription: Search\nresident: true\ndenyTools: [subagent]\nisolate: none\n---\nScout instructions\n", - )?; - std::fs::write( - repo.join("agents/ultimate.md"), - "---\nname: ultimate\ndescription: Primary\nresident: true\nisolate: none\n---\nPrimary agent\n", - )?; - std::fs::write( - repo.join("agents/coordinator.md"), - "---\nname: coordinator\ndescription: Coordinate\nisolate: none\n---\nCoordinator agent\n", + crate::common::write_config( + dir, + "standing", + serde_json::json!([ + { + "name": "scout", + "description": "Search", + "resident": true, + "denyTools": [ + "subagent" + ], + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Scout instructions" + }, + { + "name": "standing", + "description": "Primary", + "resident": true, + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Primary agent" + }, + { + "name": "coordinator", + "description": "Coordinate", + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Coordinator agent" + } + ]), )?; for args in [ vec!["init", "-b", "main"], diff --git a/host/tests/it/harness_api.rs b/host/tests/it/harness_api.rs index 30de1c0..350710c 100644 --- a/host/tests/it/harness_api.rs +++ b/host/tests/it/harness_api.rs @@ -76,21 +76,37 @@ fn prepare(dir: &Path) -> anyhow::Result<()> { repo.join("extensions/probe/server.ts"), "export default host => { globalThis.testHost = host; globalThis.subagentService = host.need({name:'subagents'}); globalThis.messageService = host.need({name:'messages'}); globalThis.lineageService = host.need({name:'lineage'}); host.implement({name:'conversations'}, {summaryModel: async () => globalThis.summaryRef, concludedIn: async () => new Set(), generatedTitle: async () => {}, setStanding: async () => {}, setAutomaticSummaries: async () => {}}); return {name:'probe'}; }", )?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"}}"#, - )?; - std::fs::write( - repo.join("agents/scout.md"), - "---\nname: scout\ndescription: Search\nresident: true\ndenyTools: [subagent]\nisolate: none\n---\nScout instructions\n", - )?; - std::fs::write( - repo.join("agents/ultimate.md"), - "---\nname: ultimate\ndescription: Primary\nresident: true\nisolate: none\n---\nPrimary agent\n", - )?; - std::fs::write( - repo.join("agents/coordinator.md"), - "---\nname: coordinator\ndescription: Coordinate\nisolate: none\n---\nCoordinator agent\n", + crate::common::write_config( + dir, + "standing", + serde_json::json!([ + { + "name": "scout", + "description": "Search", + "resident": true, + "denyTools": [ + "subagent" + ], + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Scout instructions" + }, + { + "name": "standing", + "description": "Primary", + "resident": true, + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Primary agent" + }, + { + "name": "coordinator", + "description": "Coordinate", + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Coordinator agent" + } + ]), )?; for args in [ vec!["init", "-b", "main"], diff --git a/host/tests/it/harness_foundation.rs b/host/tests/it/harness_foundation.rs index 05149b8..29eeeaa 100644 --- a/host/tests/it/harness_foundation.rs +++ b/host/tests/it/harness_foundation.rs @@ -114,12 +114,51 @@ fn channel_with_closed_stdin() -> anyhow::Result<()> { #[test] fn cli_stays_up_after_stdin_eof() -> anyhow::Result<()> { let dir = tempfile::tempdir()?; + World::open(dir.path())?; + let disk = dir.path().join("world"); + let target = crate::common::build_git(); + std::fs::create_dir_all(disk.join("bin"))?; + for binary in ["git", "tar"] { + std::fs::copy( + target.join(format!("wasm32-wasip2/release/{binary}.wasm")), + disk.join(format!("bin/{binary}.wasm")), + )?; + } + let repo = disk.join("src/sausage"); + let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../extensions"); + for extension in ["core", "models", "subagents"] { + crate::common::copy_tree( + &source.join(extension), + &repo.join("extensions").join(extension), + )?; + } + crate::common::write_config( + dir.path(), + "console", + serde_json::json!([ + {"name":"console","description":"Standing console","model":"openai/gpt-6.1-sol","prompt":"Keep the user conversation"} + ]), + )?; + for args in [ + vec!["init", "-b", "main"], + vec!["add", "."], + vec!["commit", "--no-gpg-sign", "-m", "EOF fixture"], + ] { + assert!( + Command::new("git") + .args(args) + .current_dir(&repo) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .status()? + .success() + ); + } let mut child = Command::new(env!("CARGO_BIN_EXE_sausage")) .arg("run") .arg(dir.path()) - .args(["--api-listen", "127.0.0.1:0"]) - .env("PI_PROXY_BASE_URL", "https://proxy.invalid") - .env("PI_PROXY_API_KEY", "faux-token") .env_remove("SAUSAGE_USERLAND") .stdin(Stdio::null()) .spawn()?; @@ -134,7 +173,7 @@ fn cli_stays_up_after_stdin_eof() -> anyhow::Result<()> { r.get::<_, i64>(0) }) .unwrap_or(0) - > 0 + > 1 { break; } diff --git a/host/tests/it/messages.rs b/host/tests/it/messages.rs index 4c6ccd9..940bf80 100644 --- a/host/tests/it/messages.rs +++ b/host/tests/it/messages.rs @@ -60,21 +60,37 @@ fn prepare(dir: &Path) -> anyhow::Result<()> { source.join("extensions/core/agents.ts"), repo.join("extensions/core/agents.ts"), )?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"}}"#, - )?; - std::fs::write( - repo.join("agents/scout.md"), - "---\nname: scout\ndescription: Search\nresident: true\ndenyTools: [subagent]\nisolate: none\n---\nScout instructions\n", - )?; - std::fs::write( - repo.join("agents/ultimate.md"), - "---\nname: ultimate\ndescription: Primary\nresident: true\nisolate: none\n---\nPrimary agent\n", - )?; - std::fs::write( - repo.join("agents/coordinator.md"), - "---\nname: coordinator\ndescription: Coordinate\nmodel: faux/coordinator\nisolate: none\n---\nCoordinator agent\n", + crate::common::write_config( + dir, + "standing", + serde_json::json!([ + { + "name": "scout", + "description": "Search", + "resident": true, + "denyTools": [ + "subagent" + ], + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Scout instructions" + }, + { + "name": "standing", + "description": "Primary", + "resident": true, + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Primary agent" + }, + { + "name": "coordinator", + "description": "Coordinate", + "isolate": "none", + "model": "faux/coordinator", + "prompt": "Coordinator agent" + } + ]), )?; for args in [ vec!["init", "-b", "main"], diff --git a/host/tests/it/p1.rs b/host/tests/it/p1.rs index 209596c..194852a 100644 --- a/host/tests/it/p1.rs +++ b/host/tests/it/p1.rs @@ -10,7 +10,7 @@ fn bundle() -> anyhow::Result { let key = crate::common::bundle_key(&repo)?; let stamp = bundle.join(".source-key"); if !bundle.join("bin/sh.wasm").exists() - || !bundle.join("src/sausage/agents/models.json").exists() + || !bundle.join("etc/sausage/config.yaml").exists() || std::fs::read_to_string(&stamp).ok().as_deref() != Some(key.as_str()) { if stamp.exists() { @@ -33,12 +33,11 @@ async fn bundle_copy_and_real_shell() -> anyhow::Result<()> { let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".."); let bundle = bundle()?; let dir = tempfile::tempdir()?; - let world = World::open_with_userland(dir.path(), Some(&bundle))?; + let world = World::init(dir.path(), &bundle).await?; assert!(world.root.stat("/bin/sh.wasm", true).await?.size > 0); let snapshot = dir.path().join("world/src/sausage"); for path in [ - "agents/models.json", - "agents/ultimate.md", + "config/config.yaml", "skills/README.md", "extensions/README.md", ] { @@ -58,11 +57,11 @@ async fn bundle_copy_and_real_shell() -> anyhow::Result<()> { Ok(String::from_utf8(output.stdout)?.trim().to_owned()) }; let message = git(&snapshot, &["log", "-1", "--format=%s"])?; - let revision = message.strip_prefix("Bundle source ").unwrap(); - for path in ["agents", "skills", "extensions"] { + assert_eq!(message, "Initial world source"); + for path in ["config", "skills", "extensions"] { assert_eq!( git(&snapshot, &["rev-parse", &format!("HEAD:{path}")])?, - git(&repo, &["rev-parse", &format!("{revision}:{path}")])?, + git(&repo, &["rev-parse", &format!("HEAD:{path}")])?, "bundled {path} must match the source commit" ); } @@ -197,7 +196,7 @@ async fn bundle_copy_and_real_shell() -> anyhow::Result<()> { ); let history = String::from_utf8(history)?; assert_eq!(history.lines().count(), 1); - assert!(history.contains("Bundle source ")); + assert!(history.contains("Initial world source")); let mut status = Vec::new(); assert_eq!( exec.exec( @@ -312,7 +311,7 @@ impl sausage::exec::Exec for LoaderTiming { async fn bundled_extensions_load() -> anyhow::Result<()> { let bundle = bundle()?; let dir = tempfile::tempdir()?; - let world = World::open_with_userland(dir.path(), Some(&bundle))?; + let world = World::init(dir.path(), &bundle).await?; let root = world.root.clone(); let exec = sausage::process::exec(World { root: world.root.clone(), diff --git a/host/tests/it/p3.rs b/host/tests/it/p3.rs index e06bb86..68b69e2 100644 --- a/host/tests/it/p3.rs +++ b/host/tests/it/p3.rs @@ -61,29 +61,12 @@ fn prepare(dir: &Path, all_extensions: bool) -> anyhow::Result<()> { repo.join("extensions/probe/server.ts"), "export default host => { globalThis.p3Models=host.need({name:'models'}); globalThis.p3Subagents=host.need({name:'subagents'}); globalThis.p3Workspaces=host.need({name:'workspaces'}); globalThis.p3Host=host; return {name:'probe'}; }", )?; - std::fs::create_dir_all(repo.join("agents"))?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"}}"#, - )?; - for role in ["ultimate", "coordinator", "worker", "reviewer"] { - let denial = if role == "worker" || role == "reviewer" { - "denyTools: [subagent]\n" - } else { - "" - }; - std::fs::write( - repo.join(format!("agents/{role}.md")), - format!( - "---\nname: {role}\ndescription: P3 {role}\nisolate: none\n{denial}{}---\nP3 role:{role}\n", - if role == "ultimate" { - "resident: true\n" - } else { - "" - } - ), - )?; - } + let roster: Vec = ["standing", "coordinator", "worker", "reviewer"].into_iter().map(|role| serde_json::json!({ + "name":role, "description":format!("P3 {role}"), "model":"faux/faux-1", + "isolate":"none", "resident":role == "standing", "prompt":format!("P3 role:{role}"), + "denyTools":if role == "worker" || role == "reviewer" {vec!["subagent"]} else {vec![]} + })).collect(); + crate::common::write_config(dir, "standing", serde_json::json!(roster))?; std::fs::write( repo.join("settings.json"), r#"{"lander":{"checks":["sh -c ': > /check-running; until test -f /check-release; do :; done; test -f feature.txt'"]}}"#, diff --git a/host/tests/it/p4.rs b/host/tests/it/p4.rs index 1957f2e..3628085 100644 --- a/host/tests/it/p4.rs +++ b/host/tests/it/p4.rs @@ -73,6 +73,19 @@ fn prepare(dir: &Path) -> anyhow::Result { } World::open_with_userland(dir, Some(&bundle))?; let repo = dir.join("world/src/sausage"); + for extension in ["core", "models", "subagents"] { + crate::common::copy_tree( + &source.join("extensions").join(extension), + &repo.join("extensions").join(extension), + )?; + } + crate::common::write_config( + dir, + "console", + serde_json::json!([ + {"name":"console","description":"P4 console","model":"openai/gpt-6.1-sol","prompt":"Build the requested programs","tools":["bash"]} + ]), + )?; fs::create_dir_all(repo.join("extensions/p4"))?; fs::write( repo.join("extensions/p4/server.ts"), @@ -102,18 +115,13 @@ impl Drop for Running { let _ = self.0.wait(); } } -fn round(dir: &Path, bundle: &Path, number: usize) -> anyhow::Result<()> { +fn round(dir: &Path, number: usize) -> anyhow::Result<()> { let stdout = dir.join(format!("round-{number}.stdout")); let stderr = dir.join(format!("round-{number}.stderr")); let mut child = Running( Command::new(env!("CARGO_BIN_EXE_sausage")) .arg("run") .arg(dir) - .arg("--userland") - .arg(bundle) - .args(["--api-listen", "127.0.0.1:0"]) - .env("PI_PROXY_BASE_URL", "https://proxy.invalid") - .env("PI_PROXY_API_KEY", "faux-token") .env_remove("CREDENTIALS_DIRECTORY") .stdin(Stdio::piped()) .stdout(fs::File::create(&stdout)?) @@ -229,7 +237,7 @@ fn agent_builds_rust_and_node_twice() -> anyhow::Result<()> { let bundle = prepare(dir.path())?; let mut first_hits = 0; for number in 1..=2 { - let outcome = round(dir.path(), &bundle, number); + let outcome = round(dir.path(), number); let cleanup = boxes_removed(dir.path(), &bundle); if outcome.is_err() { for stream in ["stdout", "stderr"] { diff --git a/host/tests/it/proxy_models.rs b/host/tests/it/proxy_models.rs index 00ed176..b23de83 100644 --- a/host/tests/it/proxy_models.rs +++ b/host/tests/it/proxy_models.rs @@ -96,6 +96,12 @@ async fn provider_transport_and_prices() -> anyhow::Result<()> { Ok(()) }); let dir = tempfile::tempdir()?; + let config = dir.path().join("world/etc/sausage"); + std::fs::create_dir_all(&config)?; + std::fs::write( + config.join("config.yaml"), + serde_json::to_vec(&json!({"proxy":proxy}))?, + )?; let source = format!( "globalThis.testProxy = {proxy};\n{}", include_str!("../../js/proxy-models-test-bundle.js") diff --git a/host/tests/it/subagents.rs b/host/tests/it/subagents.rs index b2997de..1e31b58 100644 --- a/host/tests/it/subagents.rs +++ b/host/tests/it/subagents.rs @@ -51,13 +51,22 @@ fn prepare(dir: &Path) -> anyhow::Result<()> { source.join("extensions/core/agents.ts"), repo.join("extensions/core/agents.ts"), )?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"}}"#, - )?; - std::fs::write( - repo.join("agents/scout.md"), - "---\nname: scout\ndescription: Search\nresident: true\ndenyTools: [subagent]\nisolate: none\n---\nScout instructions\n", + crate::common::write_config( + dir, + "scout", + serde_json::json!([ + { + "name": "scout", + "description": "Search", + "resident": true, + "denyTools": [ + "subagent" + ], + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Scout instructions" + } + ]), )?; for args in [ vec!["init", "-b", "main"], diff --git a/host/tests/it/watchdog.rs b/host/tests/it/watchdog.rs index 7f7cd70..b54688d 100644 --- a/host/tests/it/watchdog.rs +++ b/host/tests/it/watchdog.rs @@ -62,21 +62,37 @@ fn prepare(dir: &Path) -> anyhow::Result<()> { source.join("extensions/conversations/api.ts"), repo.join("extensions/conversations/api.ts"), )?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"}}"#, - )?; - std::fs::write( - repo.join("agents/scout.md"), - "---\nname: scout\ndescription: Search\nresident: true\ndenyTools: [subagent]\nisolate: none\n---\nScout instructions\n", - )?; - std::fs::write( - repo.join("agents/ultimate.md"), - "---\nname: ultimate\ndescription: Primary\nresident: true\nisolate: none\n---\nPrimary agent\n", - )?; - std::fs::write( - repo.join("agents/coordinator.md"), - "---\nname: coordinator\ndescription: Coordinate\nisolate: none\n---\nCoordinator agent\n", + crate::common::write_config( + dir, + "standing", + serde_json::json!([ + { + "name": "scout", + "description": "Search", + "resident": true, + "denyTools": [ + "subagent" + ], + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Scout instructions" + }, + { + "name": "standing", + "description": "Primary", + "resident": true, + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Primary agent" + }, + { + "name": "coordinator", + "description": "Coordinate", + "isolate": "none", + "model": "faux/faux-1", + "prompt": "Coordinator agent" + } + ]), )?; for args in [ vec!["init", "-b", "main"], diff --git a/host/tests/it/workspaces.rs b/host/tests/it/workspaces.rs index 627bdc2..bd09c08 100644 --- a/host/tests/it/workspaces.rs +++ b/host/tests/it/workspaces.rs @@ -70,14 +70,12 @@ fn prepare(dir: &Path) -> anyhow::Result<()> { repo.join("extensions/probe/server.ts"), "export default host => { globalThis.workspaceService=host.need({name:'workspaces'}); globalThis.workspaceHost=host; return {name:'probe'}; }", )?; - std::fs::create_dir_all(repo.join("agents"))?; - std::fs::write( - repo.join("agents/models.json"), - r#"{"default":{"model":"faux/faux-1"}}"#, - )?; - std::fs::write( - repo.join("agents/worker.md"), - "---\nname: worker\ndescription: Implement\nisolate: worktree\n---\nImplement\n", + crate::common::write_config( + dir, + "worker", + serde_json::json!([ + {"name":"worker","description":"Implement","model":"faux/faux-1","isolate":"worktree","prompt":"Implement"} + ]), )?; std::fs::write( repo.join("settings.json"), diff --git a/skills/README.md b/skills/README.md index e3c343e..83d0b1c 100644 --- a/skills/README.md +++ b/skills/README.md @@ -1,23 +1,29 @@ # World skills -The built-in skills live in `/src/sausage/skills/`. Repo skills live in `/.agents/skills/`. -Each skill has `name` and `description` frontmatter. The prompt lists its path. An agent reads the full file on demand. +Built-in skills live in `/src/sausage/skills/`. Project skills live in `/.sausage/skills/`. +Each skill has `name` and `description` frontmatter. +The prompt lists its path. An agent reads the full file when it needs the skill. -| Ultimate source | Sausage skill | Purpose | -| --- | --- | --- | -| how-ultimate-works | how-sausage-works | Explain branches, decisions, memory, and explicit repos without claims about a browser UI. | -| integrate-ultimate | integrate-sausage | Investigate first and adapt selected repo agents, skills, CLIs, or servers. | -| adopt-ultimate-setup | adopt-sausage-workflow | Tour approved families and the team, then adapt only selected pieces. | -| write-extension | write-extension | Change durable coordination behavior through installed contracts and standard WASI operations. | +| Skill | Purpose | +| --- | --- | +| how-sausage-works | Explain branches, decisions, memory, and explicit repositories. | +| integrate-sausage | Investigate first and adapt selected roster entries, skills, CLIs, or servers. | +| adopt-sausage-workflow | Read the live roster, then adapt only the selected workflow pieces. | +| write-extension | Change durable coordination through installed contracts and standard WASI operations. | -The port omits `ui-preview-round` and `verify-ui`. -Those skills require browser capture tools and the Ultimate preview host. P3 supplies neither. -Designer and coordinator instructions still require actual images before visual claims or required visual approval. -Without images, they report visual checks as unverified. Automated tests do not replace approval. +P3 supplies no browser capture tools. +Designer and coordinator prompts require actual images before visual claims or required visual approval. +Without images, agents report visual checks as unverified. Automated tests do not replace approval. -The port removes storage chapter changes and subscription login instructions. -Credentials remain in the host. A 403 requests host approval. -A commit to `/src/sausage` on `main` reloads the complete committed coordination snapshot. -The current task supplies files and pure parser tests, not that runtime loader. +The world has no storage chapter changes or subscription login instructions. +Managed credentials remain in the host. A 403 requests host approval. +The proxy key in `/etc/sausage/config.yaml` is the explicit exception to host-only secret storage. +A commit to `/src/sausage` on `main` reloads the complete coordination snapshot. -Run `nix develop -c node extensions/core/agents.test.ts` from the repository root to validate all skill frontmatter and bodies. +Run the pure roster and skill tests from the repository root after `npm ci --prefix host/js`: + +```sh +nix develop -c sh -c 'host/js/node_modules/.bin/esbuild extensions/core/agents.test.ts --bundle --platform=node --format=cjs --alias:yaml=./host/js/node_modules/yaml/dist/index.js --outfile=/tmp/sausage-agents-test.cjs && node /tmp/sausage-agents-test.cjs' +``` + +`cargo test -p sausage --test it -- core_ext::` checks prompt construction through the real extension loader. diff --git a/skills/adopt-sausage-workflow/SKILL.md b/skills/adopt-sausage-workflow/SKILL.md index e297cf8..652ce2a 100644 --- a/skills/adopt-sausage-workflow/SKILL.md +++ b/skills/adopt-sausage-workflow/SKILL.md @@ -1,37 +1,39 @@ --- name: adopt-sausage-workflow -description: Tour the world model families and review team, then adapt only the user’s selected pieces. +description: Tour the world roster and review team, then adapt only the user's selected pieces. --- # Adopt selected workflow pieces -Read /src/sausage/agents/models.json and all /src/sausage/agents/*.md files before the tour. -Read the explicit project repo’s instructions and check commands. +Read /etc/sausage/config.yaml before the tour. +Read the explicit project repository's instructions and check commands. Explain these pieces in one or two lines each: -- Model families select a model and thinking level for each role. +- Each roster entry selects its model, thinking level, role prompt, and tools directly. +- Every agent receives the global prompt before its role prompt. +- The configured standing agent keeps the user's conversation and receives branch reports. - The review lead combines independent correctness, simplicity, and advisory architecture reports. -- The coordinator overlay selects the lead family without copying its instructions. -- The lander checks the combined result. A push needs the owner’s authorization. -- A fresh worktree needs only the project’s required non-secret files and build steps. +- The lander checks the combined result. A push needs the owner's authorization. +- A fresh worktree needs the project's required non-secret files and build steps. Ask the user which pieces to adopt. Include None. Do not write files before the answer. -The world family file supplies default and fast through openai/gpt-6.1-sol at medium. -It supplies review through anthropic/claude-opus-5-5 at xhigh. -It supplies research, design, and lead through anthropic/claude-opus-5-5 at high. +Report the current roster values, not an assumed default team or model assignment. Use only models configured in the world. Never substitute another provider to bypass approval. -The default review team uses the review family. It trades model diversity for the approved model policy. +Edit only the selected roster entries in /etc/sausage/config.yaml. +Explain that these entries apply across the world, not only to the current project. +There are no model families or project overlays. +Keep unrelated entries intact. Never print or copy the proxy key. +Reviewer entries keep their read-only tools, immutable range rule, and report format. +Adapt correctness risks and architecture references to the actual repository. +Keep simplicity focused on minimum necessary code. Never add a replacement review lead. -Write selected repo agent files in /.sausage/agents/. Keep unrelated existing files intact. -An overlay needs name and addTools, even when addTools is empty. It must not contain tools. -Reviewer definitions keep tools: [read, bash], the immutable range rule, and the report format. -Adapt correctness risks and architecture references to the actual repo. Keep simplicity focused on minimum necessary code. -Never add a replacement reviewer lead. - -If the user selects lander or worktree behavior, inspect the installed workspace extension’s contract before configuration. -Do not invent configuration keys. Prove required commands in a disposable worktree with an explicit repo path. +If the user selects lander or worktree behavior, inspect the installed workspace extension's contract before configuration. +Do not invent configuration keys. +Prove required commands in a disposable worktree with an explicit repository path. Show the exact diff and checks before an authorized commit. Never push without authorization. -The host injects credentials. A 403 requests host approval. Do not copy secrets into worktrees or configuration. +The host injects managed credentials. A 403 requests host approval. +The proxy key in the world config is the explicit exception to host-only secret storage. +Do not copy secrets into worktrees or project configuration. diff --git a/skills/how-sausage-works/SKILL.md b/skills/how-sausage-works/SKILL.md index 54ebddf..4a8fcdd 100644 --- a/skills/how-sausage-works/SKILL.md +++ b/skills/how-sausage-works/SKILL.md @@ -9,11 +9,11 @@ Use five short beats. Ask one question through message after each beat, and wait Offer Skip the rest at every beat. If the user skips, continue to the final question. Do not claim a particular UI exists. Use the conversation and tools that the prompt supplies. -1. Explain that @ultimate is the standing agent. The user starts work there and can steer branches directly. -2. Explain the flow: user → @ultimate → coordinator → scouts, workers, designers, and reviewer → submission and configured checks. +1. Explain that the standing agent is the standing agent. The user starts work there and can steer branches directly. +2. Explain the flow: user → the standing agent → coordinator → scouts, workers, designers, and reviewer → submission and configured checks. Features need an assessment before code unless the user explicitly waived it. Pushes require authorization. 3. Ask how much control the user wants. They decide most questions, only major questions, or authorize a hands-off goal. - During an active goal, @ultimate records decisions through goal. Host credential approvals still require the user. + During an active goal, the standing agent records decisions through goal. Host credential approvals still require the user. 4. Explain memory and context. Branches start from durable memory and explicit briefs. Compact preserves a handoff. Dreams review evidence and propose improvements. They do not switch storage chapters. 5. Ask what the project does, its explicit repo path, and the first task. diff --git a/skills/integrate-sausage/SKILL.md b/skills/integrate-sausage/SKILL.md index 53e3c8e..cd11220 100644 --- a/skills/integrate-sausage/SKILL.md +++ b/skills/integrate-sausage/SKILL.md @@ -19,17 +19,18 @@ Do not copy production data or credentials. Ask before shared database changes o Offer two to four ranked changes. State the user outcome, existing code to reuse, required programs, costs, and approvals. Prefer a skill for repeated judgment, an agent for a specialist role, and a CLI or server for deterministic work. Use a coordination extension only for harness behavior, not as a new concept for world programs. -Place repo definitions in /.sausage/agents/ and repo skills in /.agents/skills/. -An addTools overlay extends an existing agent. A complete definition replaces it by name. -Never replace the review lead merely to add reviewers. Add reviewer-* definitions instead. -Read adopt-sausage-workflow for the default team and family choices. +Read the roster in /etc/sausage/config.yaml. Propose changes only to the selected entries. +Explain that roster changes affect the whole world. There are no project overlays or model families. +Place repository skills in /.sausage/skills/. +Never replace the review lead merely to add reviewers. Add reviewer-* roster entries instead. +Read adopt-sausage-workflow for the current team and model choices. Ask the user which changes to build. Do not create configuration before that choice. Pushes, paid operations, database changes, and credential approvals need explicit authority. ## Build the selected changes -Write selected agent files and skills directly. Delegate executable behavior to a coordinator through branch with the explicit repo path. +Edit selected roster entries and skills directly. Delegate executable behavior to a coordinator through branch with the explicit repo path. Use existing build and test commands from the repo. Do not introduce a package manager or workflow without evidence. Prove required preparation in a disposable worktree with authorized non-secret inputs. Use /bin programs through bash. Preserve stdout and stderr separately when you capture output. diff --git a/skills/write-extension/SKILL.md b/skills/write-extension/SKILL.md index 7a88619..e6fd54a 100644 --- a/skills/write-extension/SKILL.md +++ b/skills/write-extension/SKILL.md @@ -12,7 +12,7 @@ Do not treat uncommitted edits as proof that the live host uses new code. Before changes, read /src/sausage/AGENTS.md, the nearest extension README, and its API contracts. Read the installed loader contract before imports or lifecycle changes. If a contract is absent, report the blocker. -Copy the closest existing extension’s shape. Do not invent host APIs or use Ultimate’s browser facets. +Copy the closest existing extension’s shape. Do not invent host APIs or use Standing agent’s browser facets. Keep deterministic world operations in CLIs or servers. Use /bin programs through the documented process interface. Use standard WASI files, HTTP, and sockets. Never add an extra host import. diff --git a/userland/bundle.nu b/userland/bundle.nu index dc166ca..9f1121d 100644 --- a/userland/bundle.nu +++ b/userland/bundle.nu @@ -1,5 +1,5 @@ #!/usr/bin/env nu -# Build independent commands and a committed source snapshot of their repository. +# Build independent commands and plain source files. World creation initializes their repository. def main [destination?: path] { let here = $env.FILE_PWD let destination = ($destination | default ($here | path join .. target userland bundle) | path expand) @@ -47,27 +47,18 @@ def main [destination?: path] { if $env.LAST_EXIT_CODE != 0 { error make {msg: 'chat unit copy failed'} } '' | save --force ($units | path join multi-user.target.wants chat.service) let repo = ($here | path join .. | path expand) - let revision = (^git -C $repo rev-parse HEAD | str trim) let snapshot = ($destination | path join src sausage) if ($snapshot | path exists) { rm --recursive --force $snapshot } mkdir $snapshot let archive = ($destination | path join source.tar) - ^git -C $repo archive --output $archive HEAD host vfs userland agents skills extensions Cargo.toml Cargo.lock flake.nix flake.lock README.md AGENTS.md .gitignore + ^git -C $repo archive --output $archive HEAD host vfs userland config skills extensions Cargo.toml Cargo.lock flake.nix flake.lock README.md AGENTS.md .gitignore if $env.LAST_EXIT_CODE != 0 { error make {msg: 'source archive failed'} } ^tar -xf $archive -C $snapshot if $env.LAST_EXIT_CODE != 0 { error make {msg: 'source extraction failed'} } rm $archive - ^git -C $snapshot init --quiet --initial-branch=main - if $env.LAST_EXIT_CODE != 0 { error make {msg: 'source git init failed'} } - ^git -C $snapshot add host vfs userland agents skills extensions Cargo.toml Cargo.lock flake.nix flake.lock README.md AGENTS.md .gitignore - if $env.LAST_EXIT_CODE != 0 { error make {msg: 'source git add failed'} } - with-env { - GIT_AUTHOR_NAME: 'Sausage', GIT_AUTHOR_EMAIL: 'sausage@localhost', - GIT_COMMITTER_NAME: 'Sausage', GIT_COMMITTER_EMAIL: 'sausage@localhost', - GIT_AUTHOR_DATE: '2000-01-01T00:00:00+0000', GIT_COMMITTER_DATE: '2000-01-01T00:00:00+0000' - } { - ^git -C $snapshot commit --no-gpg-sign --quiet -m $'Bundle source ($revision)' - if $env.LAST_EXIT_CODE != 0 { error make {msg: 'source git commit failed'} } - } + let settings = ($destination | path join etc sausage) + mkdir $settings + ^cp --remove-destination ($snapshot | path join config config.yaml) ($settings | path join config.yaml) + if $env.LAST_EXIT_CODE != 0 { error make {msg: 'default config copy failed'} } print $destination } diff --git a/userland/chat/index.html b/userland/chat/index.html index 22d0632..e3cdcf7 100644 --- a/userland/chat/index.html +++ b/userland/chat/index.html @@ -80,9 +80,9 @@ function entry(record){ function select(id){selected=id;after=0;tools.clear();$('entries').replaceChildren();} async function refresh(){ try{ - const {conversations}=await api('conversations'); + const {conversations,standing}=await api('conversations'); conversations.sort((a,b)=>a.id-b.id); - if(selected===null&&conversations.length)select((conversations.find(c=>!c.parent&&!c.owner)||conversations[0]).id); + if(selected===null&&standing)select(standing.conversationId); $('conversations').replaceChildren(); const parent=c=>c.parent?.conversationId||c.owner?.conversationId||c.starter; for(const c of conversations){